多个源文件的多重定义

问题描述 投票:0回答:3

我目前正在编写一个带有多个头文件和源文件的 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"


谢谢你。

c include multiple-definition-error
3个回答
2
投票

header.h
中,你有:

void helper(){}

这是一个定义[并且仅仅是一个声明]。

您想要一份声明

void helper();

.c 文件的一个 [且仅

一个] 中,您需要一个
定义

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

0
投票
使其成为静态内联函数。 确保标头具有防护装置,防止单个翻译单元出现多个包含。

// header.h #ifndef HEADER_H #define HEADER_H static inline void helper() {} #endif
    

0
投票
用记事本打开Project文件,你会发现一个文件有2个条目。

© www.soinside.com 2019 - 2024. All rights reserved.