[英]c++ functions defined outside of class in separate .cpp file and makefile linking
I have a project using functions from a class CRandomMersenne , declared in header randomc.h ; 我有一个使用CRandomMersenne类的函数的项目,该函数在标头randomc.h中声明; the functions are defined in a different file mersenne.cpp . 这些功能在另一个文件mersenne.cpp中定义。 In my makefile I have an object *MC_funcs2.o* that uses functions from the class. 在我的makefile中,我有一个对象* MC_funcs2.o *,该对象使用类中的函数。 The source *MC_funcs2.cpp* includes the header randomc.h . 源* MC_funcs2.cpp *包含标头randomc.h 。 However the compiler complains: 但是编译器抱怨:
MC_funcs2.o:MC_funcs2.cpp:(.text+0x20): undefined reference to `CRandomMersenne::Random()' MC_funcs2.o:MC_funcs2.cpp :(。text + 0x20):对`CRandomMersenne :: Random()'的未定义引用
I understand there is something I've done wrong with declaring functions outside the class definition, including header file to use mentioned functions and maybe with the linking in the makefile. 我知道在类定义之外声明函数时,我做错了事情,包括使用提到的函数的头文件,以及makefile中的链接。 Here is a stripped down version of some of the files: 这是其中一些文件的精简版本:
makefile: 生成文件:
SpMC3: SpMC3.cpp SpMC.h mersenne.o MC_funcs2.o
g++ SpMC3.cpp MC_funcs2.o mersenne.o -o SpMC3
MC_funcs2.o: MC_funcs2.cpp SpMC.h randomc.h
g++ -c MC_funcs2.cpp mersenne.cpp
mersenne.o: mersenne.cpp randomc.h userintf.cpp
g++ -c mersenne.cpp userintf.cpp
SpMC3.cpp (main program): SpMC3.cpp(主程序):
#include "SpMC.h"
int main() {
cout << "boing" << endl;
return 0;
}
MCfuncs2.cpp (the one that doesn't compile): MCfuncs2.cpp(不编译的):
#include "SpMC.h"
#include "randomc.h"
CRandomMersenne RanGen(time(0));
void outrandom() {
ofstream out;
out << RanGen.Random() << endl;
return;
}
Any ideas? 有任何想法吗?
I would strongly advise compiling each individual source file *.c
to a object file *.o
, i.ex. 我强烈建议将每个单独的源文件*.c
编译为目标文件*.o
,即i.ex。 mersenne.cpp -> mersenne.o
. mersenne.cpp -> mersenne.o
。 This can be achieved without having to specify each object file manually. 无需手动指定每个目标文件即可实现。
CC = gcc
CFLAGS = -g -O2
OBJECTS = main.o foo.o
main : $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o main
%.o : %.c
$(CC) $(CFLAGS) -c $<
For further information on makefiles, please take a look a this tutorial or excellent SO answer in How to make a SIMPLE C++ Makefile? 有关makefile的更多信息,请查看本教程或“ 如何制作SIMPLE C ++ Makefile”中的出色SO答案。 . 。
此错误仅表示不对mersenne.cpp进行编译...请确保已对其进行编译和链接...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.