1 // test1.h 2 int a = 10; 3 struct AA 4 { 5 int a,b: 6 }; AA b(5,6); 7 int ball();
1 // test1.cpp 2 # include"test1.h" 3 4 // the following line is invalid for it will not executed( if it‘s initialization of a var, it‘s valid) 5 // a = 11; 6 7 int ball() 8 { 9 a =13; 10 b = AA(3,4); 11 return a+4; 12 }
build a lib with command line : g++ -fPIC -shared test1.cpp -o libtt.so
# include<iostream> using namespace std; extern int a; extern int b; int ball(); int main() { cout << " call ball() " << ball() <<endl; cout << "value of a " << a <<endl; cout << "value of b" << b << endl; }
to build an executable with command line: g++ test-main.cpp -L./ -ltt
Notice:
- in test-main.cpp, we can‘t use " int a" instead of "extern int a", because "int a" is a declaration, which also can be a defination.
- wahile we can use " int ball()" instread of "extern int ball()" because " int ball() " will never be seen as a defination.
- in test1.h, dont define "int a" with prefix ‘ extern "C" ‘, because in the symbol table of it‘s lib, the name of variable is the symbol
- in test-main.cpp, we assume b is of type int and succeeds, because the symbol of b is "b", has no other information
- C or C++ excutable can get the value of a/b; but if C wants to call ball() from a C++ lib, we should add the prifix " extern "C" " to "int ball()"
时间: 2024-10-12 08:36:17