简体   繁体   中英

Global static function still working in another file

I declared a global static function in one file

ac

static void Func1(void);
void Func2(void);

void Func1(void) {
    puts("Func1 Called");
}

void Func2(void) {
    puts("Func2 Called");
}

and accessed it in bc

#include <stdio.h>
#include "a.c"
void main() {
    Func1();
    Func2();
}

the program complied successfully, but as per provided information this should give error: undefined reference to Func1 . What wrong is happening here?

You don't include a source file in another, you compile and link them together.

In you case, by saying #include "ac" , you're essentially putting the whole content of ac into bc and then starting the compilation, so the static functions and their calls are present in the same translation unit. Thus, there is no issue for compiler to find the called function.

Instead, if you do something like

gcc a.c b.c -o a.out //try to compile and link together

you'll see the expected error, as in this case, ac and bc will be two separate translation units.

You declare in header files and define in .c files. So you must use header files to represent the variables or functions you defined. Instead if you use .c files then it leads to multiple definitions.I think that is why you can access that global function.

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