C++编译报错:Multiple Definitions of与First defined here问题求助
解决C++编译链接的"Multiple Definitions of"错误
问题根源
你遇到的是典型的变量多重定义问题:INPUT.h中直接定义了命名空间下的string garbage变量,每个包含该头文件的.cpp文件(main_program.cpp、read_input_data.cpp、write_output_data.cpp)在编译时都会生成这个变量的独立副本。链接阶段编译器合并目标文件时,发现同一个变量被多次定义,因此抛出错误。
修复方案
方法1:头文件声明变量,源文件定义变量(兼容所有C++版本)
这是C++传统标准解决方案,兼容性最好:
修改
INPUT.h,将变量定义改为声明
用extern关键字标记变量仅做声明,同时避免在头文件中使用using namespace std;(防止污染全局命名空间):#ifndef INPUT_H // include guard #define INPUT_H #pragma once #include <string> namespace INPUTDATA { extern std::string garbage; // 仅声明变量,不分配内存 } #endif在任意一个
.cpp文件中定义变量
比如在main_program.cpp中添加变量定义(整个程序中仅需定义一次):// main_program.cpp #include <iostream> #include <fstream> #include <string> #include "../headers/INPUT.h" #include "../headers/FUNCTIONS.h" // 定义全局变量 namespace INPUTDATA { std::string garbage; } using namespace INPUTDATA; using namespace std; int main() { read_input_data(); write_output_data(); return 0; }
方法2:使用C++17的inline变量(简洁方案)
如果你的编译器支持C++17及以上版本,可直接在头文件中将变量声明为inline,编译器会确保程序中仅存在一个变量实例:
修改INPUT.h:
#ifndef INPUT_H // include guard #define INPUT_H #pragma once #include <string> namespace INPUTDATA { inline std::string garbage; // inline变量允许在头文件中定义 } #endif
注意:若使用此方法,需在Makefile的
CFLAGS中添加-std=c++17确保编译器支持C++17标准。
验证修复
执行以下命令重新编译:
make clean && make
修改后编译链接应能正常通过。
内容的提问来源于stack exchange,提问作者Sahaj Jain
相关产品推荐
相关产品推荐

