2011-03-05 99 views
1

不幸的是我不能在这里发布所有的源代码。我可以描述结构。所有头文件都有#ifndef/#define/#endif保护。的结构如下:C++连接问题:多重定义

  • node.h - 包括在由tree.h中
  • tree.h中 - 由tree.cpp和main.cpp中
  • tree.cpp
  • 的main.cpp
  • 包括

在全局命名空间node.h,我宣布了以下独立功能:

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

(注:如图所示波纹管,路径只是一个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 

果然,虽然,它是二进制文件。我如何重构我的代码以防止此链接问题?

回答

2

如果您在.h文件中声明了正常函数,则会发生这种情况,因为它们将在每个文件中生成,这些文件将在#include之前生成。也许你打算申报inlinestatic