embarrasing problem with #include in C
Could you please solve my problem? looking at the code, it is self explanatory:
a.h:
#include"c.h"
void a()
{
printf("I am in a\n");
}
c.h:
#include<stdio.h>
void a();
void b();
main.c:
#include"c.h"
main()
{
a();
}
and gcc main.c
will g开发者_StackOverflow社区ive me:
/tmp/ccuaiUEA.o: In function `main':
main.c:(.text+0x7): undefined reference to `a'
collect2: ld returned 1 exit status
Can you please help me in a way that file extensions (.h and .c) remain unchanged?
You need to rename a.h
to c.c
and then build and run like this:
$ gcc -Wall main.c c.c -o main
$ ./main
Explanation: your a.h
is a source file, not a header, so it need to have a .c
suffix, not .h
. Its corresponding header is c.h
so by convention it should be named c.c
. When you build your executable you need to compile and link both main.c
and c.c
source files, which is why they are both included in the gcc
command line.
Including a.h
from main.c
will "fix" your issue, but that's just not recommended.
You should put your code in .c
files, not in headers.
Nothing includes a.h
. You need to add #include "a.h"
after #include "c.h"
in main.c
.
By the way, why do you put the function definition in a header file?
As a rule of thumb, never define anything in .h files. Don't put variable- or function definitions there. It makes the code messy and hard to read, and you also get countless linker problems on most compilers.
a.h should be a c.c file that includes c.h.
Include a.h
in main.c
The way it is written the content of "a.h", i.e. the function body, is never compiled nor linked to your main program.
But as a rule of thumb, function's prototypes should be in header while the function's definition should be in C file.
精彩评论