c++在linux下编译并运行

c++ compile and run in linux

本文关键字:运行 编译 linux c++      更新时间:2023-10-16

可能重复:
未定义的参考

在我的目录中,我有:

main.cpp
tree.cpp
tree.h

我已将tree.h包含在main.cpp 中

#include "tree.h"

然后在我的主要功能中,我写

tree* t=new tree()

为了编译,我会做

g++ main.cpp

但是我有错误

undefined reference to `tree::tree()'

怎么了?

您还需要编译并链接Tree源代码:

$ g++ -c -o tree.o tree.cpp
$ g++ -o test main.cpp tree.o

运行您的应用程序:

$ ./test

您可能需要为自己创建一个make文件。make文件将自动编译多个文件程序。

例如,您可以创建一个包含billz建议的行的文件"makefile"。

all:
    g++ -c -o tree.o tree.cpp
    g++ -o test main.cpp tree.o

然后,从makefile文件夹中的终端运行make将执行all部分。

有关生成文件的详细信息,请参见http://www.cs.bu.edu/teaching/cpp/writing-makefiles/

我还没有测试过上面的代码,可能需要进行一些调整。

放置标题保护,类似于

#ifndef NAME_H
#define NAME_H
//your codes
#endif