gpt4 book ai didi

c++ - 链接器错误( undefined reference )与 `static constexpr const char*` 和完美转发

转载 作者:太空狗 更新时间:2023-10-29 20:12:11 24 4
gpt4 key购买 nike

<分区>

#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应该在编译时可解析?

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

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