问题描述
我目前正在编写一个带有多个头文件和源文件的 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"
谢谢。
解决方法
在 header.h
中,您有:
void helper(){}
这是一个定义[并且不仅仅是一个声明]。
你想要一个声明:
void helper();
在您的 .c
个文件中一个[并且仅一个],您需要一个定义:
void
helper()
{
// do helpful things ...
helper_count++;
}
,
使其成为静态内联函数。 确保标头具有防止来自单个翻译单元的多个包含的保护。
// header.h
#ifndef HEADER_H
#define HEADER_H
static inline void helper() {}
#endif