您的代码格式正确。
确保您没有冲突的文件名,这些文件存在并包含您认为它们所做的事情。例如,也许你有一个Dice.cpp
空的,而你正在其他地方编辑一个新创建的。
通过删除不必要的文件来最小化可能的差异;只有main.cpp
,dice.h
和dice.cpp
.
您的错误与您的代码不匹配:"Dice::roll(int)"
. 请注意,这正在寻找一个int
,但您的函数需要一个unsigned int
. 确保您的标题匹配。
尝试以下操作:
g++ main.cpp -c
这将为main.o
main 生成已编译但未链接的代码。做同样的事情dice.cpp
:
g++ dice.cpp -c
您现在有两个需要链接在一起的目标文件。这样做:
g++ main.o dice.o
看看这是否有效。如果没有,请执行以下操作:
nm main.o dice.o
这将列出对象中的所有可用符号,并且应该为您提供如下内容:
main.o:
00000000 b .bss
00000000 d .ctors
00000000 d .data
00000000 r .eh_frame
00000000 t .text
00000098 t __GLOBAL__I_main
00000069 t __Z41__static_initialization_and_destruction_0ii
U __ZN4Dice4rollEj
U __ZNSi3getEv
U __ZNSolsEPFRSoS_E
U __ZNSolsEi
U __ZNSt8ios_base4InitC1Ev
U __ZNSt8ios_base4InitD1Ev
U __ZSt3cin
U __ZSt4cout
U __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
00000000 b __ZStL8__ioinit
U ___gxx_personality_v0
U ___main
00000055 t ___tcf_0
U _atexit
00000000 T _main
dice.o:
00000000 b .bss
00000000 d .data
00000000 t .text
00000000 T __ZN4Dice4rollEj
U _rand
U _srand
U _time
C++ 会破坏函数名称,这就是为什么一切看起来都如此怪异的原因。(注意,没有标准的修改名称的方法,这就是 GCC 4.4 的做法)。
请注意dice.o
并main.o
引用相同的符号:__ZN4Dice4rollEj
。如果这些不匹配,那就是你的问题。例如,如果我将部分更改为dice.cpp
:
// Note, it is an int, not unsigned int
int roll(int dieSize)
然后nm main.o dice.o
产生以下内容:
main.o:
00000000 b .bss
00000000 d .ctors
00000000 d .data
00000000 r .eh_frame
00000000 t .text
00000098 t __GLOBAL__I_main
00000069 t __Z41__static_initialization_and_destruction_0ii
U __ZN4Dice4rollEj
U __ZNSi3getEv
U __ZNSolsEPFRSoS_E
U __ZNSolsEi
U __ZNSt8ios_base4InitC1Ev
U __ZNSt8ios_base4InitD1Ev
U __ZSt3cin
U __ZSt4cout
U __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
00000000 b __ZStL8__ioinit
U ___gxx_personality_v0
U ___main
00000055 t ___tcf_0
U _atexit
00000000 T _main
dice.o:
00000000 b .bss
00000000 d .data
00000000 t .text
00000000 T __ZN4Dice4rollEi
U _rand
U _srand
U _time
请注意,这给出了两个不同的符号。main.o
寻找 this:__ZN4Dice4rollEj
并dice.o
包含 this __ZN4Dice4rollEi
。(最后一个字母不同)。
当试图编译这些不匹配的符号(带g++ main.o dice.o
)时,我得到:
undefined reference to `Dice::roll(unsigned int)'