简体   繁体   English

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

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

I have source code in two files. 我有两个文件的源代码。

The first file contains int main() function and declaration and usage of constexpr int square(int x) function. 第一个文件包含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";
}

The second file contains the definition of constexpr int square(int x) function. 第二个文件包含constexpr int square(int x)函数的定义。

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

When I try to compile these two files, I get the following error. 当我尝试编译这两个文件时,我收到以下错误。

$ 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

If I remove the constexpr keyword from both source files, then the program compiles and runs fine. 如果我从两个源文件中删除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

Why does the program not compile when the constexpr keyword is present? 为什么在constexpr关键字出现时程序无法编译? Why does it complain about undefined reference to square(int) when it is clearly present in 'bar.cpp' specified as command line argument to g++? 当它明确存在于指定为g ++的命令行参数的'bar.cpp'中时,为什么会抱怨对square(int)未定义引用?

When the compiler can do so, it will replace a call to a constexpr function with its resulting value. 当编译器可以执行此操作时,它将使用其结果值替换对constexpr函数的调用。 As a result, constexpr functions are implicitly inline . 因此, constexpr函数是隐式inline

Normally you should define constexpr functions in headers. 通常,您应该在标头中定义constexpr函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM