How to split a C program into multiple files?

佐手、 提交于 2019-12-18 09:59:23

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/5128664/how-to-split-a-c-program-into-multiple-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!