如何使C函数仅在其他某些。C文件中的函数可见?
假设我有一个foo1函数,它调用其他的foo2函数(在不同的。c文件中),我想从我的主函数中调用foo1,但我想要foo2对于除foo1以外的任何函数都是不可见的,像这样:
/**
foo1.c
*/
void foo1()
{
if (condition_is_true){
foo2();
}
}
/**
foo2.c
*/
#include <stdio.h>
void foo2()
{
printf("Hello world!n");
}
/**
main.c
*/
void foo1(void);
void foo2(void);
int main()
{
foo1();
foo2(); /*unresolved external*/
}
在编译
时$ cc -omain main.c foo1.c foo2.c
我希望链接器报错"对' foo2'的未定义引用"。
通常,如果您想使一个。c源代码文件中的函数在另一个。c源文件中可见,您可以将该函数的定义放入。h文件中,并将其包含在您希望它可见的。c文件中。例如:
file foo1.c
int somefunc1(some parameters)
{
Do some stuff.
}
file foo1.h
int somefunc1(some parameters);
file foo2.c
#include "foo1.h"
int foo2(Some parameters)
{
Do some stuff.
foo1(asdfasdf)
Do some more stuff.
}
这通常是你所做的。然而,你所要求的恰恰相反。我不知道为什么你想要一个未定义的引用,当链接器运行,但你已经设置你的编译方式,这些文件将被传递到链接器。因此,您唯一能做的就是在文件列表中不包含foo2.c。如果您正在使用某个主库中的内容,即使您没有指定包含文件,它仍然会被链接进来。例如:
$$$ ->more test3.c
int main(void)
{
printf("hello worldn");
return(0);
}
$$$ ->clang -std=c11 -Wall -Wextra -o test3 test3.c
test3.c:8:5: warning: implicitly declaring library function 'printf' with type 'int (const char *, ...)'
printf("hello worldn");
^
test3.c:8:5: note: please include the header <stdio.h> or explicitly provide a declaration for 'printf'
1 warning generated.
所以你所要求的我真的不认为可以或应该做。