Source file cannot find the header files

2019-09-05 11:38发布

问题:

I have looked at these links : This one and This and a couple of other similar ones. None of the answers given here are working methods are working.

I have a two source files a1.c , a2.c and two header files a1.h and a2.h . I want to include the header files in both these files (and a2.c in a1.c as there is a function I need to use from a2.c)

I have included

#include "a1.h"  
#include "a2.h"

in the source files of a1.c

I'm using GCC on Ubuntu. and using the command gcc a1.h -o a1.out -lm and that didn't work.

I tried with

gcc -c -I/Home/Documents/ctests/ a1.c -o a1.out

as well as

gcc -c a1.c -I/Home/Documents/ctests/ -o a1.out

My spellings are okay as well (there's hardly any room for error there with one letter and a number as the filename anyway).

Also, all the files are in the same folder.

I know this may be a trivial question but I am stuck on this one and would appreciate any help. I am relatively new to programming and completely new to Linux and Unix as far as using the command line goes.

Many thanks!

回答1:

gcc -c

tells gcc to compile the file to object (the .o files you see everywhere). To be linked later with some other .o files to an executable.

So what you want to do is either compile the two files separately and link them later. like this.

gcc -I"/Home/Documents/ctests/" -c a1.c
gcc -I"/Home/Documents/ctests/" -c a2.c

gcc -o myprogram a1.o a2.o 

Or just compile and link at the same time.

gcc -I"/Home/Documents/ctests/" a2.c a1.c -o myprogram

And then run your program like

path_to/myprogram 


回答2:

Compile everything, and link it together.

If all files are in one directory, this should work:

  gcc a1.c a2.c -o myapp

When you want to create separate object files, do this:

  gcc -c a1.c a2.c

Then you can then link together to create an application:

  gcc a1.o a2.o -o myapp


回答3:

Your gcc command should be like this

gcc -I/Home/Documents/ctests/ -o a1.out a1.c

and you have to include a1.h and a2.h header file in your a1.c like this

#include "a1.h"
#include "a2.h"

If you are calling some function from a2.c in your a1.c then you have to build your program in this way

gcc -I/Home/Documents/ctests/ -o a1.out a2.c a1.c