Compiling multiple C files with gcc
You should define the functions that you want to call from modules.c
into main.c
into a header file, let us say modules.h
, and include that header file in main.c
. Once you have the header file, please compile both of the files together: gcc main.c modules.c -o output
Two additional notes. First, modules.o
is an object file and it should not be included in a C source file. Second, we cannot have a C file have a .o
extension. You should actually get an error when compiling a .o
file. Something like:
$ cat t.o
int main() {
int x = 1;
return 0;
}
$
$ gcc t.o
ld: warning: in t.o, file is not of required architecture
Undefined symbols:
"_main", referenced from:
start in crt1.10.6.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
$
If you have your two source files, you can compile them into object files without linking, as so:
gcc main.c -o main.o -c
gcc module.c -o module.o -c
where the -c
flag tells the compiler to stop after the compilation phase, without linking. Then, you can link your two object files as so:
gcc -o myprog main.o module.o
This is all perfectly normal behavior, you'll usually get your makefile to compile things separately and link them at the end, so you don't have to recompile every single source file every time you change one of them.
Talking about main.o
"calling functions in" module.o
is perfectly fine, but an .o
file is not a source file, it's a compiled object file. If "put my source code in files with extension .o
" actually meant "compile my source code into files with extension .o
" then the situation would make a whole lot more sense.
program: main.o
gcc -o main main.c anotherSource.c
This works for me.