9

I am having some trouble compiling a few files using headers. Here is a breakdown of my code:

file1.c

#include "header.h"
int main() {
    func1();
    return 0;
}

file2.c

#include "header.h"
void func1() {
    ... function implementation ...
}

header.h

void func1();


The error I am getting is:

In function 'main':
undefined reference to 'func1'

Note: I am just using a simple breakdown of how my 3 files are set up. I need to get this to work with the 3 files. I am setting/including everything properly? I need to use this set up, but I am just unsure how file.c gets reference to the actually implementation of func1().

12
  • 2
    what compiler are you using ?? can you provide your compiler statement? Jun 30, 2012 at 20:21
  • 3
    If you're using gcc -o program file2.c file1.c, change this to gcc -o program file1.c file2.c. Order is important.
    – user529758
    Jun 30, 2012 at 20:28
  • Hmm, your right that this should work under normal gcc compiling. Problem is, this issue for more is from a very big project, with hundreds of files. But the structure of the problem is the same. I just thought maybe I wasn't including stuff properly, but I guess that's not the case.
    – Tesla
    Jun 30, 2012 at 20:41
  • I just tried this with gcc -- gcc -o test file2.c file1.c -- using file1.c and file2.c in both positions. Something else is afoot, I think. I'm on Ubuntu 10.04 gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1) Jun 30, 2012 at 20:53
  • 1
    @H2CO3: AFAIK, the order matters only for libraries. I.e. libs (-lnameoflib) should be specified after the sources using symbols from them, and if there are inter-lib dependencies, then order of libs matters too, or the grouping options must be used (linker then goes in a loop for the group, until all references are satisfied or no more can be resolved.)
    – mity
    Jun 30, 2012 at 21:28

1 Answer 1

4

If the error is an undefined reference to func1(), and there is no other error, then I would think it's because you have two files called header.h in your project and the other copy is being included instead of your copy with the declaration of func1().

I would check the include paths for your project and make sure that the header.h with your declaration of func1() is being included first.

1
  • This is soooooo old, but I am running into the issue and I'd appreciate help. The basic set up is the same as this question, except I am sure that correct header is being included, because some functions do not give undefined references and some do. It's just weird, and if I jeopardize the header then the code "correctly" doesn't compile. Mar 17, 2017 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.