putting function definitions in header files

后端 未结 4 488
情话喂你
情话喂你 2021-02-05 14:22

If you want to put function definitions in header files, it appears there are three different solutions:

  1. mark the function as inline
  2. mark the
4条回答
  •  梦如初夏
    2021-02-05 14:27

    As far as I know, only inline and template functions can be defined in header files.

    static functions are deprecated, and functions defined in an unnamed namespace should be used instead (see 7.3.1.1 p2). When you define a function in an unnamed namespace in a header, then every source code including that header (directly or indirectly) will have an unique definition (see 7.3.1.1 p1). Therefore, functions should not be defined in the unnamed namespace in header files (only in source files).

    The standard referenced are from the c++03 standard.

    EDIT:

    Next example demonstrates why functions and variables shouldn't be defined into unnamed namespace in headers :

    ops.hpp contains:

    #ifndef OPS_HPP
    #define OPS_HPP
    namespace
    {
    int a;
    }
    #endif
    

    dk1.hpp contains:

    #ifndef DK1_HPP
    #define DK1_HPP
    void setValue();
    void printValue();
    #endif
    

    dk1.cpp contains:

    #include "dk1.hpp"
    #include "ops.hpp"
    #include 
    
    void setValue()
    {
        a=5;
    }
    void printValue()
    {
        std::cout<

    dk.cpp contains :

    #include "dk1.hpp"
    #include "ops.hpp"
    #include 
    
    int main()
    {
        // set and print a
        setValue();
        printValue();
    
        // set and print it again
        a = 22;
        std::cout<

    Compile like this:

    g++ -ansi -pedantic -Wall -Wextra dk.cpp dk1.cpp
    

    and the output :

    5
    22
    5
    

    ops the variable a is different for the source file dk1.cpp and dk.cpp

提交回复
热议问题