Including multiple .c files in a single translation unit

855 Views Asked by At

In C is it recurrent to have .c files including other internal .c files with static variables / functions in a copy / paste manner? Like a .c file composed of many .c files where you want everything to be kept private and not declared in a header file.

Example:

a.c

static int a() {
    return 3;
}

b.c

static int b() {
    return 6;
}

c.h

int c();

c.c

#include "c.h"

#include "a.c"
#include "b.c"

int c() {
    return a() + b();
}

main.c

#include <stdio.h>

#include "c.h"

int main() {
    printf("%d\n", c())
}

To compile

clang -c c.c
clang -c main.c
clang c.o main.o -o test.exe
2

There are 2 best solutions below

0
Roman Pavelka On

Nope, this is not common. The standard way is to create new header files for a.c and b.c and include those instead of .c source files but otherwise as you did. Then you compile all sources separately and link them together, in your case:

clang -c a.c
clang -c b.c
clang -c c.c
clang -c main.c
clang a.o b.o c.o main.o -o test.exe
0
Paul Yang On

if you Rename a.c to a.h, b.c to b.h, then everything looks normal.

#include is preprocess of the compiler; it just insert the content of the target file there. no matter is .h or .c or something else.

But in convention, it not good to include the implementation file. which will ruin the source code structure.