为什么编译器会抱怨对constexpr函数的未定义引用,即使它是在另一个源文件中定义的?

Lon*_*ner 3 c++ const c++11

我有两个文件的源代码.

第一个文件包含int main()函数的功能和声明以及用法constexpr int square(int x).

// File: foo.cpp
#include <iostream>

constexpr int square(int x);

int main()
{
    int a = square(10);
    std::cout << "a: " << a << "\n";
}
Run Code Online (Sandbox Code Playgroud)

第二个文件包含constexpr int square(int x)函数的定义.

// File: bar.cpp
constexpr int square(int x)
{
    return x * x;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译这两个文件时,我收到以下错误.

$ g++ -std=c++11 bar.cpp foo.cpp
foo.cpp:4:15: warning: inline function ‘constexpr int square(int)’ used but never defined
 constexpr int square(int x);
               ^
/tmp/cc7iwVDZ.o: In function `main':
foo.cpp:(.text+0xe): undefined reference to `square(int)'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

如果我constexpr从两个源文件中删除关键字,那么程序编译并运行正常.

$ sed 's/constexpr//g' foo.cpp > foo2.cpp
$ sed 's/constexpr//g' bar.cpp > bar2.cpp
$ g++ -std=c++11 bar2.cpp foo2.cpp
$ ./a.out 
a: 100
Run Code Online (Sandbox Code Playgroud)

为什么constexpr关键字存在时程序无法编译?为什么它抱怨未定义的引用square(int)何时明确存在于指定为g ++命令行参数的'bar.cpp'中?

Yu *_*Hao 6

当编译器可以执行此操作时,它将constexpr使用其结果值替换对函数的调用.结果,constexpr函数是隐含的inline.

通常您应该constexpr在标题中定义函数.