You are not logged in.
Pages: 1
I've been having a bit of trouble making my own header files in C. I have a basic test program along the lines of:
Main Program:
#include "header.h"
int main(void){
foo();
}
Header:
void foo(void);
Header.c
#include "header.h"
defines foo()
So basically, the syntax is correct (as far as I know), but I have trouble compiling it. I get an undefined function error with gcc. Are there some command line compilation arguments I'm missing? Could someone give me a basic walkthrough of how to make/use my own header files?
Thanks.
Offline
It's most likely your compilation strategy. When you begin to break things up into mutliple files, you cannot (always) use the gcc form:
gcc main.c -o main
as that actually does 2 things at once. It compiles main.c and then links it. That is where the undefined function comes from. It is a linker error.
To avoid this there are two things you can do. The "proper" way is to split these steps manually.
gcc -c main.c
gcc -c header.c
The -c flag tells gcc ONLY to compile the code. This will produce main.o and header.o.
Now, you can link manually, and you need to link ALL objects that contain used functions. "undefined" errors result from not linking in something that contains a function used.
gcc main.o header.o -o main
Now ./main should run as expected.
Now. There is a shorthand to this... but I would recommend using the above way, just to make you more familiar with the separation of the two steps AND what kind of errors are compiler errors vs what kind of errors are linker errors.
Shorthand:
gcc main.c header.c -o main
As with the initial usage, this combines both compilation and linking steps.
Offline
Is it correct to assume that your main function is in a different .c file than header.c? Are you sure that the compiler is aware of both .c files?
edit: phrakture is too fast!
Offline
Thank you very much phrakture, that's exactly what I was hoping for. I had insisted to my teacher that it was a problem with how I was trying to compile the program, but he didn't agree with me, so it's nice to know what I had been doing wrong. I hadn't fully understood compiling the object files and linking before; I'll have to look into the process a bit more.
Offline
You should probably start reading about make too. As long as you are learning about compiling, make helps manage all those commands and file linkages. Plus I figure, if you start with it small, by the time you get to a big project, you will be good and ready.
/swogs
Open Toes; Open Mind; Open Source.
Offline
Pages: 1