I have this C compilation issue.
It took me while to understand the root cause for the issue. Although, now that i have intercepted the issue, I am not sure I fully understated the full C compilation flow logic.
I have two directoriess: inc and src
In the inc directories I have one file: test.h In the src directories I have two file: test.c and main.c
The test.c file implements a function, let call it test(), and the main.c file call this test() function.
I declared this function in the test.h file
Now, I included this test.h file only in the main.c file, in order to let the main.c file to "see" the declaration of the test() function.
when compiling:
g++ -o test.o -c test.c
g++ -o main.o -c main.c
g++ -o test test.o main.o
In the last command I get an error of "undefined reference to 'test'
After debugging this issue, I found out that the missing include of the test.h file in the test.c file resolves the issue.
In other words, I need to includes the test.h file in both source files - main.c and test.c
My question is, why? Is it not enough to include the header file, test.h file, only in the main.c file, in order to let it "see" the function declaration, and in linkage phase the compiler would "know" to associate the test() function used in the main.c file to its implementation in the test.c file?
I thought that the declaration of the test() function in the test.h file makes it "extern" declaration, and therefore it will signal the compiler to find the function implementation in linkage phase
#include
directive. That means only source file that includes a specific header file will know about the declarations in the header file. A source-file with all included header files are known as a translation unit and each translation unit is more or less stand-alone. – Some programmer dudetest.h
intest.c
there will be no way for the compiler to check that thetest()
function prototype intest.h
is correct: neither the compiler nor the linker will know if you are callingtest()
with incorrect arguments, or using an incorrect return value. – Weather Vanetest
function intest.h
matches definiton intest.c
. – rubikonx9