How to declare constexpr extern?

前端 未结 6 922
耶瑟儿~
耶瑟儿~ 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条回答
  •  -上瘾入骨i
    2020-11-29 08:21

    C++17 inline variables

    This awesome C++17 feature allow us to:

    • conveniently use just a single memory address for each constant
    • store it as a constexpr
    • do it in a single line from one header

    main.cpp

    #include 
    
    #include "notmain.hpp"
    
    int main() {
        // Both files see the same memory address.
        assert(¬main_i == notmain_func());
        assert(notmain_i == 42);
    }
    

    notmain.hpp

    #ifndef NOTMAIN_HPP
    #define NOTMAIN_HPP
    
    inline constexpr int notmain_i = 42;
    
    const int* notmain_func();
    
    #endif
    

    notmain.cpp

    #include "notmain.hpp"
    
    const int* notmain_func() {
        return ¬main_i;
    }
    

    Compile and run:

    g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
    g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
    g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
    ./main
    

    GitHub upstream.

    The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft 10.1.6 "The inline specifier":

    6 An inline function or variable with external linkage shall have the same address in all translation units.

    cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static is not given, then it has external linkage.

    See also: How do inline variables work?

    Tested in GCC 7.4.0, Ubuntu 18.04.

提交回复
热议问题