为什么编译器抱怨对constexpr函数的未定义引用,即使它是在另一个源文件中定义的
Why does the compiler complain about undefined reference to a constexpr function even though it is defined in another source file?
我有两个文件的源代码。
第一个文件包含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
函数
相关文章:
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 如何在 c++ 中定义一个将被另一个短语替换的短语?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 使用命名空间在另一个".cpp"文件中定义
- C++ 在一个源文件中使用另一个源文件中的矢量定义
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何在一个函数中定义一个变量,并在另一个函数中访问和更改它?(C++)
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- 是否可以使用另一个lua文件中定义的表,该表在当前文件中不需要作为模块
- 在另一个文件中初始化的 extern 数组中未定义的引用
- C++:如何从另一个谓词定义泛型而不是谓词
- 为什么相同的函数签名只有区别,另一个通过 const 获取参数是重新定义?
- 根据是否定义了另一个宏来评估宏
- 如何提前终止在另一个文件中定义的函数?
- 在另一个文件中定义函数后,Visual Studio 无法识别该函数
- 如何在另一个类模板中定义完全专用类的构造函数
- GLM如何在不声明内联函数并在另一个(未连接的?)文件中将其定义的函数逃脱
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- 访问另一个.cpp文件中的.cpp文件中定义的全局变量