1

不幸的是,我无法在此处发布所有源代码。我可以描述结构。所有头文件都有#ifndef/#define/#endif 保护。结构如下:

  • node.h - 包含在 tree.h 中
  • tree.h - 包含在 tree.cpp 和 main.cpp 中
  • 树.cpp
  • 主文件

在全局命名空间的 node.h 中,我声明了以下独立函数:

bool char_sort_func(Path first, Path second)
{
  return (first->label() < second->label()); 
}

(注意:如下所示,Path 只是一个 shared_ptr)当我尝试构建时,我收到一个多重定义错误,指出该函数存在于 tree.o 和 main.o 中:

> make
g++ -c -g -Wall main.cpp -I /usr/include
g++ -c -g -Wall tree.cpp  -I /usr/include
g++ -Wall -o tool tree.o main.o -L /usr/lib -l boost_program_options
main.o: In function `char_sort_func(boost::shared_ptr<Edge>, boost::shared_ptr<Edge>)':
node.h:70: multiple definition of `char_sort_func(boost::shared_ptr<Edge>, boost::shared_ptr<Edge>)'
tree.o:node.h:70: first defined here
collect2: ld returned 1 exit status
make: *** [all] Error 1

我尝试搜索所有源文件以查看是否属实,但是,我没有在任何错误的地方看到它:

> grep char_sort_func *
Binary file main.o matches   
node.h:bool char_sort_func(Path first, Path second) 
node.h:    std::sort(edges_.begin(), edges_.end(), char_sort_func);
Binary file trie.o matches

果然,它在二进制文件中。如何重组我的代码以防止出现此链接问题?

4

1 回答 1

3

如果您在.h文件中声明普通函数,就会发生这种情况,因为它们将在每个文件中生成#include。也许你的意思是宣布它inlinestatic

于 2011-03-05T00:34:54.127 回答