C++17 链接 C++11 lib 出现重复定义

C++11 实现 static constexpr 是按照const static 实现的,需要在 .cpp 中定义:

// tmp.h
class StatisTest {
public:
        static constexpr const char literal[] = "xxx literal";
};

// tmp.cc

#include "tmp.h"
const char StatisTest::literal[];

// compile with cxx11

g++ -c tmp.cc 

查看符号:

[root@63213cb4961f ~]# nm tmp.o
0000000000000000 R _ZN10StatisTest7literalE

// use_tmp.cc

#include "tmp.h"

#include <iostream>
void printliteral() {
        std::cout << StatisTest::literal << std::endl;
}
[root@63213cb4961f ~]# g++ -std=c++17 main.cc tmp.o use_tmp.o 
use_tmp.o:(.rodata._ZN10StatisTest7literalE[_ZN10StatisTest7literalE]+0x0): multiple definition of `StatisTest::literal'
tmp.o:(.rodata+0x0): first defined here
collect2: error: ld returned 1 exit status
posted @ 2024-05-28 17:37  stdpain  阅读(10)  评论(0编辑  收藏  举报