我有這些靜態成員初始化C++類的麻煩。 查看我的代碼以獲取更多信息。C++靜態成員初始化與編譯器鏈接混淆。怎麼解決?
源header.h
#ifndef HEADER_H
#define HEADER_H
#include <string>
using namespace std;
class Staff{ public: static string str;};
class Boss{ public: static string str;};
#endif
staff.cpp
#include "header.h"
string Staff::str = "(staff)";
boss.cpp
#include "header.h"
string Boss::str = "I call " + Staff::str;
的main.cpp
#include <iostream>
#include "header.h"
int main(){cout << Boss::str << endl;}
這裏是與不同的結果多編譯代碼:
預編譯:
g++ -c boss.cpp
g++ -c staff.cpp
ar rcs lib.a boss.o staff.o
ar rcs rlib.a staff.o boss.o
編譯,運行和結果:
g++ main.cpp staff.cpp boss.cpp ; ./a.out
==> I call (staff)
g++ main.cpp boss.cpp staff.cpp ; ./a.out
==> segmentation fault (core dumped)
g++ main.cpp lib.a ; ./a.out
==> segmentation fault (core dumped)
g++ main.cpp rlib.a ; ./a.out
==>segmentation fault (core dumped)
我想用庫歸檔,而不是在編譯時混淆巨大的對象。 幫我解決它們。