ridthyself
ridthyself

Reputation: 839

undefined reference when including a header file

I get an error when I include a header file, but not if I include the source file instead.

The function is defined in the source file like this:

/* in User.c */

struct User {
    const char* name;
};

struct User* addedUser(const char* name) {
    struct User* user = malloc(sizeof(struct User));
    user->name = name;
     return user;
}

And used like this:

/* in main.c */

int test_addedUser() {
    char* newName = "Fooface";
    struct User* newUser = addedUser(newName);
    assert(!strcmp(newName, newUser->name));
    return 0;
}

This works great. I am able to call test_addUser without a problem when I #include "User.c".

However, I would like to #include "User.h" instead, which is located in the same directory:

/* in User.h */

struct User {
    const char* name;
};

struct User* addedUser(const char*);

But, if I #include "User.h" instead of User.c, I get an error:

CMakeFiles/run_tests.dir/src/tests.c.o: In function `test_addedUser':
/home/rid/port/src/tests.c:(.text+0x4eb): undefined reference to `addedUser'

It seems strange to me that the reference works just fine when including the source file User.c but it is unable to reconcile User.h.

Any ideas why this might be?

Upvotes: 2

Views: 15733

Answers (2)

BIOHAZARD
BIOHAZARD

Reputation: 2043

So I created some custom lib folder for example "engine" and placed some .cpp files in it:

main.cpp
engine/sprite.cpp
engine/sprite.h
engine/unit.cpp
engine/unit.h 

So before compile cmd looked like:

g++ -o main main.cpp

After adding folder:

g++ -Iengine -o main main.cpp  engine/*cpp

And it works

Upvotes: 0

Gam
Gam

Reputation: 694

#include means that the file included is copied into the source file. So when you include your .c file, the function's code is here and it works. If you include only the header file, it's good thanks to that your functions will know each other, at least they will now they exist but they need their code to work together, so you need now to compile your two files.c together, not one by one. Maybe you're compiling by yourself :

gcc file1.c file2.c

Or with an IDE, you have to adjust the compiling options. If you want to compile the C files separatly, you have to compile them in object files (-c option with gcc), then link them.

Upvotes: 10

Related Questions