How to declare constexpr extern?

前端 未结 6 927
耶瑟儿~
耶瑟儿~ 2020-11-29 07:43

Is it possible to declare a variable extern constexpr and define it in another file?

I tried it but the compiler gives error:

De

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 08:28

    I agree with 'swang' above, but there is a consequence. Consider:

    ExternHeader.hpp

    extern int e; // Must be extern and defined in .cpp otherwise it is a duplicate symbol.
    

    ExternHeader.cpp

    #include "ExternHeader.hpp"
    int e = 0;
    

    ConstexprHeader.hpp

    int constexpr c = 0; // Must be defined in header since constexpr must be initialized.
    

    Include1.hpp

    void print1();
    

    Include1.cpp

    #include "Include1.hpp"
    #include "ExternHeader.hpp"
    #include "ConstexprHeader.hpp"
    #include 
    
    void print1() {
        std::cout << "1: extern = " << &e << ", constexpr = " << &c << "\n";
    }
    

    Include2.hpp

    void print2();
    

    Include2.cpp

    #include "Include2.hpp"
    #include "ExternHeader.hpp"
    #include "ConstexprHeader.hpp"
    #include 
    
    void print2() {
        std::cout << "2: extern = " << &e << ", constexpr = " << &c << "\n";
    }
    

    main.cpp

    #include 
    #include "Include1.hpp"
    #include "Include2.hpp"
    
    int main(int argc, const char * argv[]) {
        print1();
        print2();
        return 0;
    }
    

    Which prints:

    1: extern = 0x1000020a8, constexpr = 0x100001ed0
    2: extern = 0x1000020a8, constexpr = 0x100001ed4
    

    IE the constexpr is allocated twice whereas the extern is allocated once. This is counterintuitive to me, since I 'expect' constexpr to be more optimized than extern.

    Edit: const and constexpr have the same behaviour, with regard to allocation, therefore from that point of view the behaviour is as expected. Though, as I said, I was surprised when I came across the behaviour of constexpr.

提交回复
热议问题