6

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

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. 我看不到这里出了什么问题。

任何帮助,将不胜感激。

编译器: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. 所以我猜链接的顺序并没有造成问题。(我已经从命令中删除了一些文件以简化它)

4

2 回答 2

9

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

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;
}
于 2010-01-17T17:56:45.900 回答
0

在您的链接阶段,您是否在通过编译第一个 cpp 文件创建的目标文件中进行链接?当一个对象引用了一个未包含在被链接对象中的符号时,就会发生此类链接器错误。

编辑:我仍然有理由相信这是问题所在。在第一个文件中,是否有重新定义 load_from_file 的预处理器符号?

于 2010-01-17T17:32:26.910 回答