Paminu wrote:
I have made a lot of helping functions that I would like to have in a
seperate file. I have tried putting them in a file "functions.c". I then
have the file "myprogram.c" that contains some structs and other primary
functions.
In my make file I then have:
myprogram: myprogram.c functions.c
gcc myprogram.c -o myprogram
But that does not work. Is it really impossible to put functions in other
files?
No, but you need to declare them, and the object files must be linked
simultaneously.
functions.h:
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
void foo(void);
void bar(void);
....
#endif
functions.c:
#include "functions.h"
void foo(void) {
....
}
void bar(void) {
....
}
myprogram.c:
#include "functions.h"
int main(void) {
foo();
bar();
}
Makefile:
myprogram: myprogram.o functions.o
gcc -o myprogram myprogram.o functions.o
myprogram.o: functions.h myprogram.c
gcc -c myprogram.c
functions.o: functions.h functions.c
gcc -c functions.c
The makefile sketched here is a bit silly since it makes everything
explicit (and doesn't use variables or implicit rules), but writing
makefiles effectively is another chapter.
Lastly, "functions.c" is an awful name for a unit because almost any
unit will contain functions. It's a much better idea to split up the
program according to areas of functionality, and think of more
descriptive names. If that means creating a unit with only one function
(foo.c, bar.c...), it's still better than producing a dump.
S.