c - 多源文件的多定义
问题描述
我目前正在编写一个包含多个头文件和源文件的 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++;
}
推荐阅读
- c# - 执行插件时出现 System.MethodAccessException(Dynamics 365 在线)
- python - python请求输出中的错误编码(?)
- vue.js - 清单:行:1,列:1,语法错误。清单的公共链接已更改
- sql - SQL 参数化排序
- javascript - VSCode 停止连接到 MongoDB 服务器 - NodeJS
- flutter - 我正在尝试制作一个与极客教程作为参考的极客应用程序。我有以下错误
- matplotlib - geopandas 在使用 xlim、ylim 时控制图例大小
- ant-media-server - 一次性游戏代币未获得授权
- javascript - 对具有 htpasswd 的 url 的 Axios GET 请求
- flutter - 在颤动中发送带有地图列表的http补丁请求