C++17 連結 C++11 lib 出現重複定義

stdpain發表於2024-05-28

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

相關文章