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

Why does the compiler complain about undefined reference to a constexpr function even though it is defined in another source file?

本文关键字:另一个 定义 源文件 引用 编译器 constexpr 为什么 未定义 函数      更新时间:2023-10-16

我有两个文件的源代码。

第一个文件包含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";
}

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

// File: bar.cpp
constexpr int square(int x)
{
    return x * x;
}

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

$ 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

如果我从两个源文件中删除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

constexpr关键字存在时,为什么程序不编译?为什么它抱怨对square(int)的未定义引用,当它清楚地存在于作为g++命令行参数指定的'bar.cpp'中?

当编译器可以这样做时,它将用其结果值替换对constexpr函数的调用。因此,constexpr函数隐式地是inline

通常你应该在头文件中定义constexpr函数

相关文章: