Created
June 11, 2020 16:14
-
-
Save jlschrag/a17812e3cdd3ca77a2e065649051f2b6 to your computer and use it in GitHub Desktop.
HelloWorld from a Linux shared library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required (VERSION 3.13) | |
project (ConsumingProject) | |
add_executable (ConsumingProject "ConsumingProject.cpp" "ConsumingProject.h") | |
if (UNIX) | |
target_link_libraries(ConsumingProject "${CMAKE_DL_LIBS}") #Allows us to include dlfcn.h to link shared (dynamic) libraries | |
endif() | |
find_library(SHARED_LIB_LOCATION SharedLib PATHS ${CMAKE_BINARY_DIR}) #Assumes library's .so files have been copied into the same directory as this file | |
target_link_libraries(ConsumingProject "${SHARED_LIB_LOCATION}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ConsumingProject.h" | |
#include <dlfcn.h> | |
#include <iostream> | |
int main() | |
{ | |
void* handle = dlopen("libSharedLib.so", RTLD_NOW); | |
if (!handle) | |
{ | |
std::cout << dlerror() << std::endl; | |
} | |
void (*HelloWorld)() = (void (*)())dlsym(handle, "HelloWorld"); | |
char* error = dlerror(); | |
if (nullptr != error) | |
{ | |
std::cout << error << std::endl; | |
} | |
HelloWorld(); | |
dlclose(handle); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment