加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 链接器错误(未定义的引用)与`static constexpr const char

发布时间:2020-12-16 09:56:47 所属栏目:百科 来源:网络整理
导读:参见英文答案 Undefined reference to static constexpr char[]????????????????????????????????????5个 #include iostreamusing namespace std;templatetypename T void print(T mX) { std::cout std::forwardT(mX) std::endl; }struct SomeStruct{ static
参见英文答案 > Undefined reference to static constexpr char[]????????????????????????????????????5个

#include <iostream>
using namespace std;

template<typename T> void print(T&& mX) 
{
    std::cout << std::forward<T>(mX) << std::endl;  
}

struct SomeStruct
{
    static constexpr const char* someString{"hello!"};
    SomeStruct()
    {
        print(someString);
    }
};

int main() 
{
    SomeStruct s{};
    return 0;
}

clang -std = c 1y ./code.cpp -o code.o

/tmp/code-a049fe.o: In function `SomeStruct::SomeStruct()’:
./code.cpp:(.text._ZN10SomeStructC2Ev[_ZN10SomeStructC2Ev]+0xa):
undefined reference to `SomeStruct::someString’ clang: error: linker
command failed with exit code 1 (use -v to see invocation)

g -std = c 1y ./code.cpp -o code.o

/tmp/ccyrTsjS.o: In function `SomeStruct::SomeStruct()’:
code.cpp:(.text._ZN10SomeStructC2Ev[_ZN10SomeStructC5Ev]+0xd):
undefined reference to `SomeStruct::someString’ collect2: error: ld
returned 1 exit status

为什么会发生此链接器错误?是不是someString应该在编译时可解析?

此外,如果用cout<<替换print(someString),则不会发生错误. someString;

解决方法

因为您正在参考该变量是使用odr并且这需要一个超出定义的定义:

constexpr const char* SomeStruct::someString;

see it working live.

从草案C 14标准第3.2节[basic.def.odr]:

A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying
the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.20) that does not invoke any nontrivial
functions and,if x is an object,ex is an element of the set of potential results of an expression e,
where either the lvalue-to-rvalue conversion (4.1) is applied to e,or e is a discarded-value expression […]

例如,以下替代打印不会使用someString:

template<typename T> void print(T mX) 
{
    std::cout << mX << std::endl;  
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读