我目前正在编写一个带有多个头文件和源文件的 C 程序。 我遇到了函数 foo 的多重定义的问题。
我知道我违反了单一定义规则,但我不太明白 确定如何解决这个问题。我有两个对象的源文件, obj1.c 和 obj2.c。由于 header.h i 包含在多个 .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