这是map_test.h文件
#ifndef _MAP_TEST_H
#define _MAP_TEST_H
#include <map>
#include <string>
using std::map;
using std::string;
map<string, string> map_config;
void init_map_config();
#endif
这是map_test.cpp文件
#include "map_test.h"
void init_map_config()
{
map_config.insert({"123", "123"});
map_config.insert({"456", "456"});
map_config.insert({"789", "789"});
}
这是main.cpp文件
#include <iostream>
#include "map_test.h"
using std::cout;
using std::endl;
int main()
{
init_map_config();
for (auto it = map_config.begin(); it != map_config.end(); it++)
cout << it->first << " " << it->second << endl;
cout << endl;
}
编译:
g++ -c map_test.cpp -o map.o -std=c++11
g++ -c main.cpp -o main.o -std=c++11
编译都是成功的,链接过程出错:
g++ map.o main.o -o main
此时出错:
main_test.o:(.bss+0x0): `map_config'被多次定义
map_test.o:(.bss+0x0):第一次在此定义
collect2: error: ld returned 1 exit status
为什么会报错?
因为违背了ODR。map_config定义在头文件中,并且是外部链接。这个头文件分别被两个源文件包含,这导致链接时map_config在两个目标文件中有定义。
解决方案是将定义移到源文件中,在头文件中只留下纯声明。