How do I link two header files and 3 c files into a single executable in C programming?

Viewed 366

I have been given to create two header files, h1.h and h2.h; two c files, a1.c and a2.c; and one main file, mainfile.c. a1 file includes h1 header file, a2 includes h2 header file and mainfile includes both header files. Now I want to link them together to get a single executable .exe file.

I know that if only 1 header file (x.h) is present with two c files (a1.c and a2.c), we can use:

gcc -c a1.c
gcc -c a2.c
gcc -o x_exe a1.o a2.o
./x_exe

Can anyone suggest something of the same format for my problem?

2 Answers

Generally speaking, you compile each .c file into a .o file, then link the .o files into an executable.

So for your specific example you would compile the source files as follows:

gcc -c a1.c
gcc -c a2.c
gcc -c mainfile.c

And link as follows:

gcc -o x_exe a1.o a2.o mainfile.o

You don't need to worry about header files when you compile unless they're in a different directory from the source, then you would use the -I option to specify that location.

This question should not be answered by asking for magic incantations of commands you do not understand. You should understand what each command does, and then you can write them yourself. gcc -c SomeName.c will compile the file SomeName.c and produce an object file named SomeName.o. Compilation includes reading the files included with #include statements and treating those as part of the source code to be compiled. So the header files are processed as part of compiling the source files. You do not need to adjust the commands for them.

Then gcc -o OutputName Name1.o Name2.o Name3.o… links together the listed object files and creates an executable file named OutputName. Again, no adjustment for header files is necessary.

So you do not need to be concerned with header files when using compiler commands. (Header files will matter when you use make or similar tools that invoke the compiler for you. That is because those tools have features to recompile source files only when the source code has changed since the corresponding object file was created. Since changing code in a header file can change the resulting object file, these tools need to know which header files a source file includes.)

Related