How can I define a C function in one file, then call it from another?
You would put a declaration for the function in the file func1.h
, and add #include "func1.h"
in call.c
. Then you would compile or link func1.c
and call.c
together (details depend on which C system).
Use a Forward Declaration
For example:
typedef struct
{
int SomeMemberValue;
char* SomeOtherMemberValue;
} SomeStruct;
int SomeReferencedFunction(int someValue, SomeStruct someStructValue);
int SomeFunction()
{
SomeStruct s;
s.SomeMemberValue = 12;
s.SomeOtherMemberValue = "test string";
return SomeReferencedFunction(5, s) > 12;
}
There is a feature that allows you to reuse these forward declarations called Header Files. Simply take the forward declarations, place them in the header file, then use #include
to add them to each C source file you reference the forward declarations in.
/* SomeFunction.c */
#include "SomeReferencedFunction.h"
int SomeFunction()
{
SomeStruct s;
s.SomeMemberValue = 12;
s.SomeOtherMemberValue = "test string";
return SomeReferencedFunction(5, s) > 12;
}
/* SomeReferencedFunction.h */
typedef SomeStruct
{
int SomeMemberValue;
char* SomeOtherMemberValue;
} SomeStruct;
int SomeReferencedFunction(int someValue, SomeStruct someStructValue);
/* SomeReferencedFunction.c */
/* Need to include SomeReferencedFunction.h, so we have the definition for SomeStruct */
#include "SomeReferencedFunction.h"
int SomeReferencedFunction(int someValue, SomeStruct someStructValue)
{
if(someStructValue.SomeOtherMemberValue == NULL)
return 0;
return someValue * 12 + someStructValue.SomeMemberValue;
}
Of course, to be able to compile both source files, and therefore the entire library or executable program, you'll need to add the output of both .c files to the linker command line, or include them in the same "project" (depending on your IDE/compiler).
Many people suggest that you make header files for all your forward declarations, even if you don't think you'll need them. When you (or other people) go to modify your code, and change the signature of functions, it will save them time from having to modify all of the places where the function is forward-declared. It may also help save you from some subtle bugs, or at least confusing compiler errors.