multiple definition error including c++ header file with inline code from multiple sources

前端 未结 6 1187
孤城傲影
孤城傲影 2020-12-01 04:41

I have a c++ header file containing a class. I want to use this class in several projects, bu I don\'t want to create a separate library for it, so I\'m putting both methods

6条回答
  •  粉色の甜心
    2020-12-01 04:57

    These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable).

    The first example isn't inline and so if this header is included in multiple translation units then you will have multiple definitions and linker errors.

    Also, headers should really always be guarded to prevent multiple definition errors in the same translation unit. That should convert your header to:

    #ifndef EXAMPLE_H
    #define EXAMPLE_H
    
    //define your class here
    
    #endif
    

提交回复
热议问题