我想知道C文件是否可以在另一个脚本(通过头文件)中包含包括,并且也可以独立运行(通过具有自己的主函数)。也就是说,可以包含C文件以将其功能提供给另一个C脚本,但本身也可以直接运行以提供一些替代功能。可否包含C文件也可以直接运行?
例如,一个python脚本可以做到这一点;
def functionsToBeImported():
# code to be run by an importing script
pass
if __name__ == '__main__':
# code to be run by this script independently
pass
此代码可以被导入(import ABOVESCRIPT
)由另一个Python文件给访问functionsToBeImported
,或独立运行(python ABOVESCRIPT.py
)到if
块内执行的代码。
我已经尝试通过myScript.c为此在C:
#include "myScript.h"
void functionsToBeImported() {
}
int main (int narg, char* varg[]) {
}
myScript.h:
#ifndef MY_SCRIPT_H_
#define MY_SCRIPT_H_
void functionsToBeImported();
#endif // MY_SCRIPT_H_
但试图包括这个anotherScript.c:
#include "myScript.h"
int main (int narg, char* varg[]) {
functionsToBeImported();
}
,并试图通过
gcc -std=c99 -c myScript.c
gcc -std=c99 -c anotherScript.c
gcc -std=c99 -o anotherScript anotherScript.o myScript.o -lm
编译给人是一个编译错误
duplicate symbol _main in:
myScript.o
anotherScript.o
我怎样才能做到这一点的“双用途”的脚本?
一个main()来统治它们。 –
我想到了一种方法来稍微复制你正在说的内容并在下面编辑我的答案。 –