【发布时间】:2013-11-25 09:59:25
【问题描述】:
我有带有声明的 hpp 文件:
namespace X {
class Y {
public:
[other functions]
inline float basicFunction();
int someFunction();
[other functions]
};
}
在cpp文件中:
namespace X {
[implementations etc.]
inline float Y::basicFunction() {
return someValue * someMath / moreMath;
}
int Y::someFunction() {
return basicFunction() * 100;
}
[other functions]
}
我在其他 cpp 文件中使用它,但我认为这不是问题。编译:
g++ -c someclass.cpp -o someclass.o -std=c++11
g++ -c main.cpp -o main.o -std=c++11
g++ main.o someclass.o -o main -std=c++11 -O0
抛出错误:
main.o: In function `main':
main.cpp:(.text+0x4d9): undefined reference to `X::Y::someFunction()'
为什么?我怎样才能正确编译它?
我知道someFunction() 没用,但这被多次调用,我就是喜欢这种方式。
上面的所有代码都不是真实的,所以可能有错误,但在我的程序上它(我认为)是正确的
我尝试了很多组合(两个函数具有相同的返回类型,都内联,没有内联等)但没有效果。
【问题讨论】:
-
为什么
Y::basicFunction()在您的 CPP 文件中内联? -
main中的调用代码是什么样的? -
你真正的编译命令输出
someclass.o和main.o,而不是someclass和main? -
为了记录,我们真的不在乎代码是否真实,只要它 (a) 编译,并且 (b) 重现问题。
-
@WhozCraig - 这必须仅在 HPP 中内联声明?没关系,现在我删除了内联,问题仍然存在。帖子中的代码无法编译,原因很明显;) @ChrisMantle - 只是创建对象
X::Y obj和obj.function()@MikeSeymour - 是的(见编辑)