首先在这里定义gcc的多重定义

时间:2013-10-30 06:54:14

标签: c++ gcc linker include multiple-definition-error

我有这些文件

consumer.cpp
consumer.hpp
defines.hpp
main.cpp
makefile
producer.cpp
producer.hpp

这是define.hpp文件

#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

这个defined.hpp文件包含在producer.hpp和consumer.hpp中。 producer.hpp和consumer.hpp文件分别包含在producer.cpp和consumer.cpp中,还包括main.cpp中。 编译时我收到错误。

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

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

如何解决这个问题?

1 个答案:

答案 0 :(得分:34)

在C ++(以及C语言)中,声明定义等变量之类的东西之间存在差异。您在头文件中所做的是定义变量,这意味着包含头文件的每个源文件都将具有定义。

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

所以在头文件中也可以这样做。

extern pthread_mutex_t set_queue_mutex;
extern pthread_cond_t  condition_var;

extern std::queue<int> q;

然后在单个源文件中放置定义(现在你拥有的)。