Splitting a group of functions into an include file in C?

I know that this is common in most languages โ€‹โ€‹and possibly in C. Can C handle splitting multiple functions into a separate file and including them?

Functions will also rely on other included files. I want the code to retain all the functionality, but the code will be reused in several C scripts, and if I change it, I donโ€™t want to go through each script and change it there too.

+3
source share
4 answers

Definitely! What you are describing is header files. You can learn more about this process, but I will talk about the basics below.

functions.h, :

int return_ten();

functions.c, :

int return_ten()
{
    return 10;
}

main.c functions.h :

#include <stdio.h>
#include "functions.h"

int main(int argc, char *argv[])
{
    printf("The number you're thinking of is %d\n", return_ten());

    return 0;
}

, functions.h , main.c.

, , . , , . , cmd: gcc main.c functions.c, a.out, .

+4

, .c. #include , , , .c.

+1

, , :

int func2(int x){
/*do some stuff */
return 0;
}

, . , , , . func2.h :

#ifndef HEADER_FUNC2_H
#define HEADER_FUNC2_H
int func2(int x);
#endif /*HEADER_FUNC2_H*/

#ifndef HEADER_FUNC2_H , , , . func2.c :

int func2(int x){
/*do some stuff */
return 0;
}

func2, . #include "func2.h". , , func2 randomfile.c, :

#include "func2.h"
/* rest of randomfile.c */
func2(1);

- , .

+1

, .

(, , ,...), #include.

, "#include" , ( , ).

, , , , ! myfuncs.lib ( libmyfuncs.a) myfuncs.h.

, , .

, , .

0

Source: https://habr.com/ru/post/1747989/


All Articles