g++ 编译失败,Cmake 没有

g++ fails to compile, Cmake does not

EDIT:已找到答案,这是一个简单的错误。我不觉得这是重复的,因为我知道错误表明什么(主函数无法找到对对象 class 的引用),我只是认为我已经正确地包含它并且需要另一组眼睛指出我的 makefile 行中的错误。

如果我使用了错误的术语,或者我误解了一些简单的东西,我提前道歉。我稍微熟悉 C 和 C#,这是我尝试 C++ 的尝试。代码中还有其他问题,例如命名不一致,但请忽略这些问题,因为它们不是手头的问题。我也在restructuring/redocumenting这个项目的过程中所以请原谅。

我有什么

我一直在使用 vim 编写一个小型 C++ 应用程序,并使用 g++ 编译它。它一直工作到一定程度。这个错误对我来说没有意义,所以我决定尝试 Clion 来尝试调试它,但令我惊讶的是,它按预期构建和 运行。

从终端进入项目根目录(比 src 高一级)和 运行 make:

g++ -c src/item.cpp -o obj/item.o
g++ -c src/hero.cpp -o obj/hero.o
g++ -c src/main.cpp -o obj/main.o
g++ -o oChre.exe obj/hero.o obj/main.o -lm
obj/main.o: In function `main':
main.cpp:(.text+0x467): undefined reference to Hand::Hand(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
main.cpp:(.text+0x49e): undefined reference to `Item::getName[abi:cxx11]()'
collect2: error: ld returned 1 exit status
makefile:7: recipe for target 'program' failed
make: *** [program] Error 1

Clion 中,我只需单击 Build运行,然后项目的构建和 运行 完全符合我的预期。

我怀疑是问题所在

我的makefile如下:

CC=g++
EXT=o
PURGE=rm

#The main bin
program: item.o hero.$(EXT) main.$(EXT)
    $(CC) -o oChre.exe obj/hero.$(EXT) obj/main.$(EXT) -lm
main.o:
    $(CC) -c src/main.cpp -o obj/main.o

#Creatures
hero.o:
    $(CC) -c src/hero.cpp -o obj/hero.o

#items
item.o:
    $(CC) -c src/item.cpp -o obj/item.o

clean:
    $(PURGE) obj/*.$(EXT) *.exe

我怀疑 Clion 没有使用我的 makefile,因为 IDE 通常能够自行决定编译什么以及如何编译。这就是我认为Clion成功运行ning的原因。

什么能解决我的问题

我希望有人能回答以下一个或两个问题:

  1. 为什么 g++ 不能正确编译?我的 makefile 有问题还是我的编译器配置不正确?我希望这个项目将来会扩展,所以值得维护我自己的 makefile 还是我应该把它留给 IDE.
  2. 为什么 Clion 会编译我的代码?我可以只获取它生成的 makefile 并将其放入我的 repo 中以便其他人可以编译它吗?

如果我遗漏了一些重要的东西,请询问或者我有 GitHub 上的所有代码。

您的 link 命令丢失 item.o

#The main bin
program: item.o hero.$(EXT) main.$(EXT)
    $(CC) -o oChre.exe obj/hero.$(EXT) obj/main.$(EXT) -lm

应该是

#The main bin
program: item.o hero.$(EXT) main.$(EXT)
    $(CC) -o oChre.exe obj/item.o obj/hero.$(EXT) obj/main.$(EXT) -lm