gpt4 book ai didi

c++ - 对非成员函数的 undefined reference - C++

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:00 25 4
gpt4 key购买 nike

我在头文件中有以下内容。

namespace silc{
class pattern_token_map
{
/* Contents */
};

pattern_token_map* load_from_file(const char*);
}

在 CPP 文件中(这有适当的包含)

pattern_token_map* load_from_file(const char* filename)
{
// Implementation goes here
}

在另一个 CPP 文件中。这已经包含了所有正确的内容。

void some_method()
{
const char* filename = "sample.xml";
pattern_token_map* map = load_from_file( filename ); // Linker complains about this.
}

我收到一个链接器错误,指出对 load_from_file 的 undefined reference 。我看不出这里出了什么问题。

如有任何帮助,我们将不胜感激。

编译器:G++操作系统:Ubuntu 9.10

编辑

这是使用的链接器命令。

g++ -L/home/nkn/silc-project/third_party/UnitTest++ -o tests.out  src/phonetic_kit/pattern_token_map.o  tests/pattern_token_map_tests.o  tests/main.o -lUnitTest++

错误来自 pattern_token_map_tests.o,该函数在 pattern_token_map.o 中可用。所以我想链接的顺序不是问题。 (我从命令中删除了一些文件以简化它)

最佳答案

当你实现它的时候,你必须确保你实现了正确的功能:

namespace silc {
pattern_token_map* load_from_file(const char* filename) {
// Implementation goes here
}
}

如果您改为这样做:

using namespace silc; // to get pattern_token_map
pattern_token_map* load_from_file(const char* filename) {
// Implementation goes here
}

那么您将定义一个新函数,而不是 silc::load_from_file。

避免在函数范围之外使用指令(“using namespace ...;”),作为一般准则:

using namespace silc; // outside function scope: avoid

silc::pattern_token_map* // qualify return type
random_function(silc::pattern_token_map* p) { // and parameters
using namespace silc; // inside function scope: fine
pattern_token_map* p2 = 0; // don't have to qualify inside the function
// if you want to use the using directive
silc::pattern_token_map* p3 = 0; // but you can always do this
return 0;
}

关于c++ - 对非成员函数的 undefined reference - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2081905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com