Commit 9afe2ae8 authored by gonczor's avatar gonczor

Part 3 - linux

parent 5c002030
all:
g++ -Wall -fPIC -shared -Wl,-soname,libmymath -Wl,-init,init mymath.cpp -o libmymath.so.1.0 -lc
#include <iostream>
#include "mymath.h"
void init() {
printf("Initializing mymath\n");
}
void destroy(){
printf("Destroying mymath\n");
}
int add(int x, int y){
std::cout << "Adding\n";
return x + y;
}
int sub(int x, int y){
std::cout << "Subtracting\n";
return x - y;
}
extern "C" void init() __attribute__((constructor));
extern "C" void destroy() __attribute__((destructor));
extern "C" int add(int, int);
extern "C" int sub(int, int);
all:
g++ -Wall -Iinclude -Llib src/main.cpp -lmymath -o bin/test
extern "C" int add(int, int);
extern "C" int sub(int, int);
Initializing mymath
Initializing mymath
Adding
Mymath adding. 3+4=7
Subtracting
Mymath subtracting 3-4=-1
Destroying mymath
#include <cstdio>
#include "mymath.h"
int main(){
printf("Mymath adding. 3+4=%d\n", add(3, 4));
printf("Mymath subtracting 3-4=%d\n", sub(3, 4));
return 0;
}
all:
g++ -rdynamic -o bin/main src/main.cpp -ldl
adding 3+4=Adding
7
subtracting 3-4=Subtracting
-1
#include <iostream>
#include <dlfcn.h>
int main() {
void* lib_handle;
int (*add)(int, int);
int (*sub)(int, int);
lib_handle = dlopen("/usr/local/lib/libmymath.so", RTLD_LAZY);
if(!lib_handle) {
std::cout << "Did not find libmymath\n";
return 1;
}
add = (int(*)(int, int))dlsym(lib_handle, "add");
sub = (int(*)(int, int))dlsym(lib_handle, "sub");
if(!add || !sub){
std::cerr << "Could not load functions\n";
return 2;
}
std::cout << "adding 3+4=" << (*add)(3, 4) << std::endl;
std::cout << "subtracting 3-4=" << (*sub)(3, 4) << std::endl;
dlclose(lib_handle);
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment