Skip to content

Instantly share code, notes, and snippets.

@roachsinai
Last active February 23, 2023 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roachsinai/0faf85c405a618a65fa552ad222e6e07 to your computer and use it in GitHub Desktop.
Save roachsinai/0faf85c405a618a65fa552ad222e6e07 to your computer and use it in GitHub Desktop.
void PrintA(void);
void PrintB(void);
int main(int argc, char *argv[])
{
PrintA();
PrintB();
return 0;
}
g++ libA.cpp -fPIC -shared -o libA.so
g++ libB.cpp -fPIC -shared -o libB.so
# https://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html
g++ -L/home/xq -Wl,-rpath=/home/xq -Wall -o a.out tt.cpp -lA -lB
# ./a.out
Constructor
Constructor
LibA:0x7f21c8087049 0x7f21c808417a 1
LibB:0x7f21c8087049 0x7f21c808417a 1
Destructor
Destructor
The results above means only only Data instance, but constructor and destructor has been run twice.
#ifndef SHARED_HEADER_H_
#define SHARED_HEADER_H_
#include <iostream>
struct Data {
Data(void) {std::cout << "Constructor" << std::endl;}
~Data(void) {std::cout << "Destructor" << std::endl;}
int FuncDefinedByLib(void) const;
};
extern const Data data;
#endif
#include "data_.h"
const Data data;
int Data::FuncDefinedByLib(void) const {return 2;}
void PrintA(void) {
std::cout << "LibA:" << &data << " "
<< (void*)&Data::FuncDefinedByLib << " "
<< data.FuncDefinedByLib() << std::endl;
}
#include "data_.h"
const Data data;
int Data::FuncDefinedByLib(void) const {return 2;}
void PrintB(void) {
std::cout << "LibB:" << &data << " "
<< (void*)&Data::FuncDefinedByLib << " "
<< data.FuncDefinedByLib() << std::endl;
}
@roachsinai
Copy link
Author

  • Each process has its own address space, meaning that there is never any memory being shared between processes (unless you use some inter-process communication library or extensions).
  • The One Definition Rule (ODR) still applies, meaning that you can only have one definition of the global variable visible at link-time (static or dynamic linking).

https://stackoverflow.com/a/19374253/6074780

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment