Подтвердить что ты не робот

Множество определений, определяемых здесь gcc

У меня есть эти файлы

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

здесь файл определяет .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

Этот файл define.hpp включен в файлы manufacturer.hpp и consumer.hpp. файлы manufacturer.hpp и consumer.hpp, соответственно, включены в файлы produc.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 [email protected] $^ -lpthread -ggdb
.PHONY : clean
clean:
    rm -rf main *.swf *.o

Как решить эту проблему?

4b9b3361

Ответ 1

В С++ (а также в C) существует разница между объявлением и определением таких вещей, как переменные. То, что вы делаете в файле заголовка, определяет переменные, а это означает, что каждый исходный файл, содержащий заголовочный файл, будет иметь определения.

В файле заголовка вы должны объявлять только переменные, а затем в одном исходном файле определить их.

Итак, в файле заголовка, например,

extern pthread_mutex_t set_queue_mutex;
extern pthread_cond_t  condition_var;

extern std::queue<int> q;

И затем в одном исходном файле укажите определения (что у вас есть).