0

So to simplify, let's say I have a Page.h file with the following...

#ifndef PAGE_H
#define PAGE_H

typedef struct Pgmap{
    int test;
}Page;

void printPage();
#endif

Where the Page.c defines printPage() and has...

#include "Page.h"

And, I have another .c/.h pair of files that use the struct/function above.

In the Test.h I...

#include "Page.h"

, and my Test.c has

#include "Test.h"

At this point I can use my Page struct, but when I try to use printPage() I get an "undefined reference to 'printPage()' error when I try to compile.

So why is it that my includes work for the struct, but not the functions? If it makes any difference my gcc is gcc(SUSE Linux) 4.6.2

JoeManiaci
  • 435
  • 3
  • 15

2 Answers2

0

It works because the header contains the declaration of the structures, but the code for the functions is in the C file. You need to link the compiled C files (called "object files") together.

For instance, compile "Page.c" into "Page.h", then when building "Test.c", also link it against "Page.o" since that module's functions are needed.

In C, just because you #include "something.h" in your C file, the compiler doesn't automatically know how to find the definitions of the things that are declared in the header (such as any functions or external variables).

The compiler only sees the text of the header, pasted into where the #include happens, basically. There is no magic way for it to find the code. You might not even have a corresponding C file, since C supports distributing binaries, i.e. pre-compiled libraries.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

My best guess, is that you are not linking in the module that contains printPage().

When compiling a module, the compiler only knows what exists based on the headers. The layout of the struct is known from the headers, but the contents of the function are not known.

You must make sure to include that other module in, when your application is linked. Or, make printPage() be an inline function.

Lompican
  • 213
  • 2
  • 9