Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a C program into multiple files?

Tags:

c

codeblocks

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?

like image 841
amin Avatar asked Feb 26 '11 17:02

amin


People also ask

Can you have multiple C files?

A large C or C++ program should be divided into multiple files. This makes each file short enough to conveniently edit, print, etc. It also allows some of the code, e.g. utility functions such as linked list handlers or array allocation code, to be shared with other programs.

Should I split my code into multiple files?

Splitting your code into multiple files is a great way to produce smaller, more focused files. Navigating theses smaller files will be easier and so will understanding the content of each of these files.


1 Answers

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; } 
like image 113
Matteo Italia Avatar answered Nov 07 '22 11:11

Matteo Italia