Originally posted by jnusa
I'm not able to compile without including the matching *.c file.
That's not the way to do it, though it may work. #including is for header files, which should only contain:
- Other #includes
- struct (or class) definitions
- function prototypes
In other words: things the compiler needs to know, but no code (inline member functions of a C++ class being the exception).
Is it even possible to use a function, with just declaring the function prototype?
Yes, there nothing wrong with that. Sometimes there are good reasons to do that (e.g. functions that call eachother recursively, but which should not be available outside the C-file they're in).
For programs larger than, say, a book example, it is normally recommended to put function prototypes in a header *.h) file, and include it in c-files that need the definitions/prototypes that are in the header.
Now about your main problem:
When you have a program that is split into seperate C-files (.c), you compile them seperately into object-files (.o). The object-files contain the compiled machine-code, but they are not executable: they need to be linked
together and some added code/information to become one executable file.
When you have a one-c-file program, and do "gcc -o program program.c", the compiler is smart enough to do both the compiling and linking in one go.
Here's a basic example of a two c-file + one header file program:
/* hello.h */
#define TEXT_TO_PRINT "Hello Denmark!"
/* hello.c */
/* hello_main.c */
/* Note double quotes ( " " ) instead of < > for #including
* header files that are part of *your* program, as opposed
* to headers that belong to libraries on the system.
Now, first compile the two c-files into object-files (.o).
(note the -c option to gcc to tell it to compile only and not try to link (which would fail, because hello.c doe not have a main() function):
gcc -Wall -c -o hello_main.o hello_main.c
gcc -Wall -c -o hello.o hello.c
Then do the linking:
gcc -Wall -o hello_program hello.o hello_main.o
Now you can run the program with:
To automate this procedure, makefiles are normally made to provide information what needs to be done. When you have made such a makefile, just typing "make" at the shell-prompt does everything needed. If done properly, make then also knows when not to compile if it is not needed. This is the case when the sources (.h and .c) have not changed since the last object file was created from them.
Make is another subject on its own right..