I want to write my C functions in 2 separate .c files and use my IDE (Code::Blocks) to compile everything together.
How do I set that up in Code::Blocks?
How do I call functions in one .c
file from within the other file?
In general, you should define the functions in the two separate .c
files (say, A.c
and B.c
), and put their prototypes in the corresponding headers (A.h
, B.h
, remember the include guards).
Whenever in a .c
file you need to use the functions defined in another .c
, you will #include
the corresponding header; then you'll be able to use the functions normally.
All the .c
and .h
files must be added to your project; if the IDE asks you if they have to be compiled, you should mark only the .c
for compilation.
Quick example:
Functions.h
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
/* ^^ these are the include guards */
/* Prototypes for the functions */
/* Sums two ints */
int Sum(int a, int b);
#endif
Functions.c
/* In general it's good to include also the header of the current .c,
to avoid repeating the prototypes */
#include "Functions.h"
int Sum(int a, int b)
{
return a+b;
}
Main.c
#include <stdio.h>
/* To use the functions defined in Functions.c I need to #include Functions.h */
#include "Functions.h"
int main(void)
{
int a, b;
printf("Insert two numbers: ");
if(scanf("%d %d", &a, &b)!=2)
{
fputs("Invalid input", stderr);
return 1;
}
printf("%d + %d = %d", a, b, Sum(a, b));
return 0;
}