g++ 链接问题

_画船听雨眠 2017-11-04 06:03:05

#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.h


#include "map_test.h"
void init_map_config()
{
map_config.insert({"123", "123"});
map_config.insert({"456", "456"});
map_config.insert({"789", "789"});
}

以上是map_test.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;
}

以上是main.cpp

编译
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.o:(.bss+0x0): `map_config'被多次定义
map.o:(.bss+0x0):第一次在此定义
collect2: error: ld returned 1 exit status


这是为什么呢?
...全文
113 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Davidsdu 2017-11-05
  • 打赏
  • 举报
回复
全局变量定义在.h文件中,在多个地方引用该头文件时,会造成重定义。 所以全局变量一般定义在.cpp文件中。 如果定义在头文件中,可以使用static来限制全局变量的作用域。
开心秋水 2017-11-05
  • 打赏
  • 举报
回复
当一个头文件被多个cpp文件包含时,这个头文件中不能出现非const的全局变量,以及非inline的全局函数
小竹z 2017-11-05
  • 打赏
  • 举报
回复
楼主一定认为自己已经加了#ifndef _MAP_TEST_H保护宏,就不会会报这个错误了。这是对#ifndef _MAP_TEST_H的错误理解,这个宏本身的作用是避免在同一个编译单元里重复,在多个编译单元里就无能为力了,通常情况下,一个cpp文件就是一个编译单元

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧