首页 > 解决方案 > 多源文件的多定义

问题描述

我目前正在编写一个包含多个头文件和源文件的 C 程序。我一直遇到函数 foo 的多重定义的问题。

我了解我违反了单一定义规则,但我不太确定如何解决此问题。我有两个对象 obj1.c 和 obj2.c 的源文件。因为 header.h 包含在多个 .c 文件中,所以会导致此错误。

除了消除除 main.c 之外的所有 .c 文件之外,还有其他解决方法吗?

//header.h (with include guards)
void helper(){}

//obj1.h
// Include function definitions for obj1.c

//obj1.c
#include "obj1.h"
#include "header.h"

//obj2.h
// Include function definitions for obj2.c

//obj2.c
#include "obj2.h"
#include "header.h"

//main.c
#include "obj1.h"
#include "obj2.h"


谢谢你。

标签: cincludemultiple-definition-error

解决方案


header.h中,您有:

void helper(){}

这是一个定义[而不仅仅是一个声明]。

你想要一个声明

void helper();

在您的一个[并且只有一个].c文件中,您需要一个定义

void
helper()
{
     // do helpful things ...
     helper_count++;
}

推荐阅读