Pergunta

I have a newbie question about the C programming language. I have looked around to find the answer in similar questions but I failed to figure it out.

Assume a simple project consisting of two dirs: src and test. The source and header files are defined by src/main.c, test/foo.h and test/foo.c.

src/main.c:

#include "../test/foo.h"

int main (void) {
    int a = VAR; /* works, recognizes declared macro */
    some_function(a); /* doesn't work, "undefined reference" */
}

test/foo.h:

#ifndef FOO_H
#define FOO_H

void some_function(int a);    
#define VAR 2;

#endif

test/foo.c (redundant but to be complete):

#include "foo.h"
#include <stdlib.h>

void some_function(int a) {
    printf("%d", ++a);
}

I created the project in Eclipse and I also compile with it, I figured it wasn't a linking error since the macro gets recognized but the method is not callable.

The reason why I'm using different directories is because I have a lot of files and would like my test code to be separate from my main source code. Note that src and test have the same parent directory.

Any ideas what's going on here? Am I missing something very obvious?

Any help would be much appreciated, thanks in advance!

edit: I'm working on a (Debian) Linux machine and Eclipse uses the gcc compiler.

edit2: Thanks to H2CO3's answer I learned it is indeed a linking error. Since compiling and linking manually every time is quite an overhead, I was wondering if anyone knows how to teach Eclipse to link executables from different directories?

--------------------- SOLUTION ---------------------

edit3: Lol the solution was very easy after all, all I had to do was create a "new source folder" rather than a "new folder". I feel stupid but thanks to you all for replying, H2CO3 in particular!

Foi útil?

Solução

I figured it wasn't a linking error since the macro gets recognized but the method is not callable.

Non sequitur. Macros are expanded in the preprocessing phase. (And as such, they have nothing to do with linkage at all.) You do have a linker error.

What you have to do is compile both files then link them together, so something like this should work:

gcc -Wall -o dir_one/foo.o dir_one/foo.c
gcc -Wall -o dir_two/bar.o dir_two/bar.c
gcc -o my_program dir_one/foo.o dir_two/bar.o

Also, read this SO question/answer and/or this article to understand how the steps of the compilation process work together. (These are almost the same for C and C++, it's only the name mangling that usually differs.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top