简体   繁体   中英

Including multiple .c files in a single translation unit

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

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

if you Rename a.c to ah, b.c to bh, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM