为了简化我的代码,我把下面的代码片段来解释我的问题:如何优雅地共享两个源文件之间的const char数组?
def.h
#ifndef _DEF_H_
#define _DEF_H_
const char draw[] = "Draw on the canvas:"
#endif
circle.c
#include "def.h"
void draw_circle(void)
{
printf("%s %s", draw, "a circle.");
}
的main.c
#include "def.h"
int main(void)
{
printf("%s %s", draw, "nothing.");
}
问题是在编译时没有问题,但由于重新定义了const char数组,draw[]
可能会在链接时失败。
如何防止此问题在两个源文件之间共享一个常量字符数组,而无需将它们放入单个编译单元中,方法是在main.c
的顶部添加#include"circle.c"
?
可能吗?
除非你犯了一个错字,否则'main.c'的顶部不需要包含'circle.c'和'def.c'。保留'def.h'并创建一个单独的编译单元,命名为'def.c',就像@YuHao指出的那样。不要忘记在def.c中包含'def.h'以避免声明/定义不匹配的风险。 –