【发布时间】:2017-06-13 04:32:06
【问题描述】:
我正在尝试编译一个包含类头的主函数。主函数以及类 cxx 文件使用一个名为“SayHello”的辅助函数。但是,如果我在主文件和类 cxx 文件中包含帮助文件“Hello.h”,则会出现多重定义错误。我在下面放了一些最小的例子。你能帮帮我吗?
干杯, 安德烈亚斯
Main.cxx:
#include "Class.h"
#include "Hello.h"
int main(int argc, char **argv){
SayHello();
return 0;
}
类.h
#ifndef CLASS_H
#define CLASS_H
class Class {
public:
Class();
~Class();
};
#endif
类.cxx
#include "Class.h"
// #include "Hello.h" //with this it breaks!
Class::Class(){
// SayHello(); //with this it breaks!
}
你好.h
#ifndef HELLO_C
#define HELLO_C
#include <iostream>
void SayHello(){
std::cout<<"hello!"<<std::endl;
}
#endif
我的生成文件:
# Compiler
CXX = $(shell root-config --cxx)
# Compiler flags
ROOTCFLAGS := $(shell root-config --cflags)
ROOTLIBS := $(shell root-config --libs)
CFLAGS = -Wall ${ROOTCFLAGS} ${INCLUDE_PATH}
LFLAGS = -O3 ${ROOTLIBS} -lHistPainter
# Targets
EXE = Main
OBJS = Main.o Class.o
# Processing
# -------------------------------------
all: ${OBJS} ${EXE}
@echo "Done"
${EXE}: ${OBJS}
@echo "Making executable $(notdir $@)"
${CXX} ${CFLAGS} ${OBJS} ${LFLAGS} -o $@
${EXE}.o: ./${EXE}.cxx
@echo "Compiling $(notdir $<)"
${CXX} $(CFLAGS) -c $< -o $@
%.o: ./%.cxx ./%.h
@echo "Compiling $(notdir $<)"
${CXX} $(CFLAGS) -c $< -o $@
clean:
@echo "Cleaning"
@rm -f ./Main
@rm -f ./Main_cxx.so
@rm -f ./Main_cxx.d
@rm -f ./*.o
@rm -f ./*ACLiC_dict_rdict.pcm
【问题讨论】:
-
创建
hello.h和hello.cpp,并用与你的类相同的方式分离“sayHello”的声明和定义 -
或者,因为这是 C++,所以将 SayHello 函数定义为
inline。 -
谢谢大家!我是新来的,所以我现在才看到你的回复,可能没有对赞成票和其他东西做出相应的反应。我要学那个!干杯!
-
请注意,您在 Hello.h 中的包含保护可能应该命名为
HELLO_H而不是HELLO_C。