How to split a C program into multiple files?

CCodeblocks

C Problem Overview


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?

C Solutions


Solution 1 - C

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaminView Question on Stackoverflow
Solution 1 - CMatteo ItaliaView Answer on Stackoverflow