Skip to content

Instantly share code, notes, and snippets.

@jlschrag
Created June 11, 2020 16:14
Show Gist options
  • Save jlschrag/a17812e3cdd3ca77a2e065649051f2b6 to your computer and use it in GitHub Desktop.
Save jlschrag/a17812e3cdd3ca77a2e065649051f2b6 to your computer and use it in GitHub Desktop.
HelloWorld from a Linux shared library
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}")
cmake_minimum_required(VERSION 3.13) #3.13 was what I had on my WSL install.
project(SharedLib VERSION 0)
add_library(SharedLib SHARED "")
set_target_properties(SharedLib PROPERTIES VERSION ${PROJECT_VERSION})
set_target_properties(SharedLib PROPERTIES SOVERSION 1) #API Version
target_sources(SharedLib
PUBLIC
SharedLib.h
SharedLib.cpp
InterfaceTypes.h
)
#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;
}
#include "SharedLib.h"
#include <iostream>
void HelloWorld()
{
std::cout << "Hello World" << std::endl;
}
#pragma once
extern "C"
{
void HelloWorld();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment