首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >多重定义这里第一次定义的是gcc

多重定义这里第一次定义的是gcc
EN

Stack Overflow用户
提问于 2013-10-30 14:54:14
回答 1查看 48.7K关注 0票数 20

我有这些文件

代码语言:javascript
复制
consumer.cpp
consumer.hpp
defines.hpp
main.cpp
makefile
producer.cpp
producer.hpp

这是文件defines.hpp

代码语言:javascript
复制
#ifndef DEFINES_HPP
#define DEFINES_HPP

#include <cassert>
#include <pthread.h> 
#include <queue>
#include <stdlib.h>
#include <string>
#include <unistd.h>

pthread_mutex_t set_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  condition_var = PTHREAD_COND_INITIALIZER;

std::queue<int> q;

#endif // DEFINES_HPP

此defines.hpp文件包含在producer.hpp和consumer.hpp中。producer.hpp和consumer.hpp文件分别包含在producer.cpp和consumer.cpp中,但尚未包含到main.cpp中。编译时,我得到一个错误。

代码语言:javascript
复制
g++ -o main producer.cpp consumer.cpp main.cpp producer.hpp consumer.hpp defines.hpp -lpthread -ggdb
/tmp/ccctuRp7.o: In function `__gnu_cxx::new_allocator<int>::destroy(int*)':
/home/vardan/test/consumer.cpp:8: multiple definition of `set_queue_mutex'
/tmp/cciGccft.o:/home/vardan/test/producer.cpp:8: first defined here
/tmp/ccctuRp7.o: In function `std::deque<int, std::allocator<int> >::front()':
/home/vardan/test/consumer.cpp:12: multiple definition of `condition_var'
/tmp/cciGccft.o:/home/vardan/test/producer.cpp:11: first defined here
/tmp/ccctuRp7.o: In function `global::consumer::entry_point(void*)':
/home/vardan/test/consumer.cpp:17: multiple definition of `q'
/tmp/cciGccft.o:/home/vardan/test/producer.cpp:17: first defined here
/tmp/ccKCxptM.o: In function `main':
/home/vardan/test/main.cpp:8: multiple definition of `set_queue_mutex'
/tmp/cciGccft.o:/home/vardan/test/producer.cpp:8: first defined here
/tmp/ccKCxptM.o: In function `main':
/home/vardan/test/main.cpp:13: multiple definition of `condition_var'
/tmp/cciGccft.o:/home/vardan/test/producer.cpp:11: first defined here
/tmp/ccKCxptM.o: In function `main':
/home/vardan/test/main.cpp:25: multiple definition of `q'
/tmp/cciGccft.o:/home/vardan/test/producer.cpp:17: first defined here
collect2: error: ld returned 1 exit status
make: *** [main] Error 1

这是我的makefile

代码语言:javascript
复制
main : producer.cpp consumer.cpp main.cpp producer.hpp consumer.hpp defines.hpp
    g++ -o $@ $^ -lpthread -ggdb
.PHONY : clean
clean:
    rm -rf main *.swf *.o

如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-30 14:56:44

在C++中(以及在C中),声明和定义变量之类的东西是有区别的。您在头文件中所做的是定义变量,这意味着包括头文件的每个源文件都将具有这些定义。

在头文件中,您应该只声明变量,然后在单个源文件中定义它们。

所以在头文件中,例如

代码语言:javascript
复制
extern pthread_mutex_t set_queue_mutex;
extern pthread_cond_t  condition_var;

extern std::queue<int> q;

然后在单个源文件中放入定义(如您现在所拥有的)。

票数 39
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19675685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档