构建模块化程序

时间:2013-12-20 14:57:44

标签: c

我已经决定构建一个模块化程序但是我在C中实现了这个失败。这是我的程序不会链接。我相信我失败了构建我的文件之间的依赖关系。这样做的“正确”方式如何?

这有点鸡/蛋的问题。我需要定义struct module并且main.c需要能够访问module_event并且event.c需要能够访问module_main。

使用这个示例代码,由于多个定义,我得到一个链接器错误,我可以避免使用“内联”,但这不是我想做的事情。

event.h

#include "main.h"
void event_cmd(void);
module module_event = {.cmd = &event_cmd};

EVENT.C

#include "event.h"
#include "main.h"
void event_cmd(void)
{
 /* */
}

main.h

typedef struct {
     void (* cmd)(void)
} module;

void main_cmd(void);
module module_main = {.cmd = &main_cmd};

的main.c

include "main.h"
include "event.h"
void main_cmd(void)
{
 /* */
}

1 个答案:

答案 0 :(得分:2)

问题是module_event在全球范围内event.cmain.c都已定义。这会导致链接问题,因为符号定义了两次,链接器不知道它需要链接到哪个符号。要解决 -

在event.h中

extern module module_event;

在event.c中

module module_event = {.cmd = &event_cmd};

这里重要的是定义可以在event.cmain.c中提供,但不能在两者中提供。

相关问题