undefined reference when including a header file

12,607

#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.

Share:
12,607

Related videos on Youtube

ridthyself
Author by

ridthyself

An admin and a bureaucrat. Here: fill out these forms and I'll be right with you.

Updated on July 05, 2022

Comments

  • ridthyself
    ridthyself almost 2 years

    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?

  • ridthyself
    ridthyself almost 7 years
    You were right, my code was sound, but I did not configure my linker correctly. Thanks!