gpt4 book ai didi

c++ - 为什么编译器会提示对 constexpr 函数的 undefined reference ,即使它是在另一个源文件中定义的?

转载 作者:太空狗 更新时间:2023-10-29 20:23:38 26 4
gpt4 key购买 nike

我在两个文件中有源代码。

第一个文件包含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 关键字时程序无法编译?当它明确存在于指定为 g++ 的命令行参数的“bar.cpp”中时,为什么它会提示对 square(int) 的 undefined reference ?

最佳答案

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

通常您应该在 header 中定义 constexpr 函数。

关于c++ - 为什么编译器会提示对 constexpr 函数的 undefined reference ,即使它是在另一个源文件中定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32031271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com