1

当我尝试编译我的代码时,我得到:

thread-support.cpp: At global scope:
thread-support.cpp:18: error: redefinition of ‘Semaphore* Mutex’
thread.h:15: error: ‘Semaphore* Mutex’ previously declared here
thread-support.cpp:19: error: redefinition of ‘Semaphore* FreePots’
thread.h:16: error: ‘Semaphore* FreePots’ previously declared here
thread-support.cpp:20: error: redefinition of ‘Semaphore* Mother’
thread.h:18: error: ‘Semaphore* Mother’ previously declared here
thread-support.cpp:21: error: redefinition of ‘Semaphore* Nap’
thread.h:20: error: ‘Semaphore* Nap’ previously declared here
thread-support.cpp:22: error: redefinition of ‘int* availPots’
thread.h:21: error: ‘int* availPots’ previously declared here
thread-support.cpp:23: error: redefinition of ‘int* emptyPots’
thread.h:22: error: ‘int* emptyPots’ previously declared here
thread-support.cpp:24: error: redefinition of ‘int* totalPots’
thread.h:24: error: ‘int* totalPots’ previously declared here

为了空间,我只包含了我的包含我的包含和全局变量。如果您希望我发布整个文件,请告诉我。

这是thread.h:

#pragma once

#include "ThreadClass.h"
#include "thread-support.cpp"

extern Semaphore *Mutex;
extern Semaphore *FreePots; 
extern Semaphore *Mother;
extern Semaphore *Nap;
extern int *availPots;
extern int *emptyPots;
extern int *totalPots;

这是thread.cpp:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include "thread.h"

这是线程支持.cpp

#include <iostream>
#include <string.h>
#include <stdio.h>
#include "thread.h"

Semaphore *Mutex;
Semaphore *FreePots;
Semaphore *Mother;
Semaphore *Nap;
int *availPots;
int *emptyPots;
int *totalPots;

这是thread-main.cpp:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "thread.h"

这是我的生成文件:

CC       = c++
FLAGS    =
CFLAGS   = -g -O2
DFLAGS   = -DPACKAGE=\"threadsystem\" -DVERSION=\"1.0\" -DPTHREAD=1 -DUNIX_MSG_Q=1 -DSTDC_HEADERS=1
IFLAGS   = -I/local/eit-linux/apps/ThreadMentor/include
TMLIB    = /local/eit-linux/apps/ThreadMentor/Visual/libthreadclass.a
TMLIB_NV    = /local/eit-linux/apps/ThreadMentor/NoVisual/libthreadclass.a

OBJ_FILE = thread.o thread-support.o thread-main.o
EXE_FILE = prog4

${EXE_FILE}: ${OBJ_FILE}
    ${CC} ${FLAGS}  -o ${EXE_FILE}  ${OBJ_FILE} ${TMLIB_NV} -lpthread

thread.o: thread.cpp
    ${CC} ${DFLAGS} ${IFLAGS} ${CFLAGS} -c thread.cpp

thread-support.o: thread-support.cpp
    ${CC} ${DFLAGS} ${IFLAGS} ${CFLAGS} -c thread-support.cpp

thread-main.o: thread-main.cpp
    ${CC} ${DFLAGS} ${IFLAGS} ${CFLAGS} -c thread-main.cpp

Visual: ${OBJ_FILE}
    ${CC} ${FLAGS}  -o ${EXE_FILE}  ${OBJ_FILE} ${TMLIB} -lpthread

clean:
    rm -f ${OBJ_FILE} ${EXE_FILE}

我已经尝试了我能想到的一切来解决这个问题,但我无法通过谷歌搜索找到这个问题的答案。我是 C++ 新手,但我认为这#pragma once是我需要的。

4

1 回答 1

4

你有

#include "thread-support.cpp"

标题 thread.h中,这会导致问题。不要包含它,而是单独编译并链接它。(Makefile 已经正确完成了,所以只需从标题中删除包含)

于 2013-11-14T21:19:33.060 回答