How can a C++ header file include implementation?

前端 未结 7 1751
有刺的猬
有刺的猬 2020-11-28 02:51

Ok, not a C/C++ expert by any means, but I thought the point of a header file was to declare the functions, then the C/CPP file was to define the implementation.

How

7条回答
  •  伪装坚强ぢ
    2020-11-28 03:48

    C++ standard quotes

    The C++17 N4659 standard draft 10.1.6 "The inline specifier" says that methods are implicitly inline:

    4 A function defined within a class definition is an inline function.

    and then further down we see that inline methods not only can, but must be defined on all translation units:

    6 An inline function or variable shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (6.2).

    This is also explicitly mentioned in a note at 12.2.1 "Member functions":

    1 A member function may be defined (11.4) in its class definition, in which case it is an inline member function (10.1.6) [...]

    3 [ Note: There can be at most one definition of a non-inline member function in a program. There may be more than one inline member function definition in a program. See 6.2 and 10.1.6. — end note ]

    GCC 8.3 implementation

    main.cpp

    struct MyClass {
        void myMethod() {}
    };
    
    int main() {
        MyClass().myMethod();
    }
    

    Compile and view symbols:

    g++ -c main.cpp
    nm -C main.o
    

    output:

                     U _GLOBAL_OFFSET_TABLE_
    0000000000000000 W MyClass::myMethod()
                     U __stack_chk_fail
    0000000000000000 T main
    

    then we see from man nm that the MyClass::myMethod symbol is marked as weak on the ELF object files, which implies that it can appear on multiple object files:

    "W" "w" The symbol is a weak symbol that has not been specifically tagged as a weak object symbol. When a weak defined symbol is linked with a normal defined symbol, the normal defined symbol is used with no error. When a weak undefined symbol is linked and the symbol is not defined, the value of the symbol is determined in a system-specific manner without error. On some systems, uppercase indicates that a default value has been specified.

提交回复
热议问题