constexpr函数的未定义符号 [英] Undefined symbols for constexpr function

查看:632
本文介绍了constexpr函数的未定义符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译以下代码时,我得到一个链接器错误:架构x86_64的未定义符号:Foo(),引用自:main.o中的_main using LLVM 4.2。



此行为仅在函数标记为 constexpr 时才会发生。当函数标记为 const 时,程序会正确编译和链接。为什么声明函数 constexpr 导致链接器错误?



(我意识到这样写函数doesn' t)

main.cpp

/ p>

  #include< iostream> 
#includetest.hpp

int main()
{
int bar = Foo();
std :: cout<< bar<< std :: endl;

return 0;
}

test.hpp
$ b

  constexpr int Foo(); 

test.cpp


$ b b

  #includetest.hpp

constexpr int Foo()
{
return 42;
}


解决方案


为什么声明函数 constexpr 导致链接器错误?


因为 constexpr 函数隐式地 inline 。根据C ++ 11标准的第7.1.5 / 2节:


A constexpr 在声明一个不是构造函数的函数时使用的说明符声明函数
是一个 constexpr 函数。类似地,在构造函数声明中使用的 constexpr 说明声明
构造函数是一个 constexpr 构造函数。 constexpr 函数和 constexpr 构造函数默认为
inline

根据第7.1.2 / 4节, >


内联函数应在每个翻译单元中定义,并且在每个翻译单元中使用它,并且在每种情况下都有相同的定义
(3.2)。 [...]



When I attempt compiling the following code I get a linker error: Undefined symbols for architecture x86_64: "Foo()", referenced from: _main in main.o using LLVM 4.2.

This behavior only occurs when the function is marked constexpr. The program compiles and links correctly when the function is marked const. Why does declaring the function constexpr cause a linker error?

(I realize that writing the function this way doesn't give the benefit of compile-time computation; at this point I am curious why the function fails to link.)

main.cpp

#include <iostream>
#include "test.hpp"

int main()
{
    int bar = Foo();
    std::cout << bar << std::endl;

    return 0;
}

test.hpp

constexpr int Foo();

test.cpp

#include "test.hpp"

constexpr int Foo()
{
    return 42;
}

解决方案

Why does declaring the function constexpr cause a linker error?

That is because constexpr functions are implicitly inline. Per Paragraph 7.1.5/2 of the C++11 Standard:

A constexpr specifier used in the declaration of a function that is not a constructor declares that function to be a constexpr function. Similarly, a constexpr specifier used in a constructor declaration declares that constructor to be a constexpr constructor. constexpr functions and constexpr constructors are implicitly inline (7.1.2).

Per Paragraph 7.1.2/4, then:

An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [...]

这篇关于constexpr函数的未定义符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆