Here are my codes for PoC:
a.h: which implements a singleton method to create A instance
#pragma once
class A
{
public:
int a;
static A& Instance() {
static A a;
return a;
}
};
b.h: which declares a function will try to create an A instance inside, and output the address of it.
#pragma once
void test_b();
b.cc: The implementation of test_b
#include "b.h"
#include <iostream>
#include "a.h"
void test_b() {
auto &a = A::Instance();
std::cout << "a address in test_b: " << (void *)(&a) << std::endl;
}
and c.cc: test_c
which do the same things as test_b
, and call test_b
and test_c
in main
to check if the singleton is working.
#include <iostream>
#include "a.h"
#include "b.h"
void test_c() {
auto &a = A::Instance();
std::cout << "a address in test_c: " << (void *)(&a) << std::endl;
}
int main() {
test_b();
test_c();
return 0;
}
I using the b.cc to build a shared library libb.so in windows(libb.dll), and using c.cc to create the test_app which links with the shared library.
I've tested the above codes in Linux and Windows(MinGW), but I've got different results.
Under linux the output is like:
a address in test_b: 0x601174
a address in test_c: 0x601174
And under MinGW the output is like:
a address in test_b: 0x7ff87df93070
a address in test_c: 0x7ff731ef30b0
The makefile I used for the build.
Makefile:
test_app: c.cc libb.so
g++ -o $@ $^ -lb
libb.so: a.h b.cc
g++ -o $@ -fPIC -shared b.cc
Makefile.mingw
test_app.exe: c.cc libb.dll
g++ -o $@ $^ -lb -L.
libb.dll: a.h b.cc
g++ -o $@ -fPIC -shared b.cc
I know implementing Singleton in the header file is not a good practice, but if anyone could help to explain why?