开发者

C++ linking issue: multiple definition

Unfortunately I cannot post all of the source code here. I can describe the structure though. All header files have #ifndef/#define/#endif guards. The structure is as follows:

  • node.h - included by tree.h
  • tree.h - included by tree.cpp and main.cpp
  • tree.cpp
  • main.cpp

In node.h in the global namespace, I declare the following free standing function:

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

(Note: as shown bellow, a Path is just a shared_ptr) When I try to build, I get a multiple definition error saying that the function is present in both tree.o and 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

I tried searching all of the source files to see if that was true, however, I don't see it in any wrong places:

> 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

Sure enough though, it is in the binary files. How can I restructure my code to prevent this linking issue?


This will happen if you declare normal functions in a .h file, because they will be generated in every file that #includes it. Perhaps you meant to declare it inline or static?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜