Skip to content

Instantly share code, notes, and snippets.

@soda92
Last active November 25, 2024 12:22
Show Gist options
  • Save soda92/9c2f8e703e7e95142b4dddebd7089afb to your computer and use it in GitHub Desktop.
Save soda92/9c2f8e703e7e95142b4dddebd7089afb to your computer and use it in GitHub Desktop.
distributing MSYS2 programs https://stackoverflow.com/a/79222920/12291425
targets := prog.exe my_library.dll my_plugin.dll
CXX := g++
CXXFLAGS := -c -g -O0 -MMD -pedantic -Wall -Wextra -Wconversion -Wno-unused -Wno-unused-parameter -Werror -Wfatal-errors -UNDEBUG -std=c++17 -Wno-missing-braces -Wno-sign-conversion
all: $(targets)
.PHONY: all
%.dll: %.o
$(CXX) -shared -g -O0 -o $@ $<
# by implicit rule, my_plugin.o will be compiled from my_plugin.cpp
# by implicit rule, my_library.o will be compiled from my_library.cpp
prog.exe: prog.o my_library.dll
g++ -o prog.exe prog.o -g -O0 -L. -lmy_library
files := $(wildcard *.dll *.o *.d *.exe)
distfiles := $(wildcard dist/*.dll dist/*.exe)
clean:
rm $(files) 2>/dev/null || true
rm $(distfiles) 2>/dev/null || true
.PHONY: clean
dist: all
rm -r dist 2>/dev/null || true
mkdir dist 2>/dev/null || true
cp *.dll *.exe dist
@# extra $ is needed in awk in makefile
cd dist; ldd $(targets) | grep /ucrt64 | awk '{print $$3}' | xargs -i cp {} .
@# if you make sure you are running UCRT, you can remove the following line
cd dist; ldd $(targets) | grep /mingw64 | awk '{print $$3}' | xargs -i cp {} .
cd dist; explorer . || true
.PHONY: dist
#include <iostream>
__declspec(dllexport)
int
my_library_function(int arg)
{
std::cout << "~~~~ entering " << __func__ << " ~~~~\n";
std::cout << "arg=" << arg << '\n';
std::cout << "~~~~ leaving " << __func__ << " ~~~~\n";
return 2*arg;
}
#include <iostream>
extern "C" __declspec(dllexport)
int
my_plugin_function(int arg)
{
std::cout << "~~~~ entering " << __func__ << " ~~~~\n";
std::cout << "arg=" << arg << '\n';
std::cout << "~~~~ leaving " << __func__ << " ~~~~\n";
return 2*arg;
}
#include <windows.h>
#include <iostream>
__declspec(dllimport)
int
my_library_function(int arg);
int
main()
{
std::cout << "~~~~ entering " << __func__ << " ~~~~\n";
int result=my_library_function(123);
std::cout << "result=" << result << '\n';
std::cout << "~~~~ still in " << __func__ << " ~~~~\n";
HINSTANCE lib=LoadLibrary("my_plugin.dll");
if(lib)
{
FARPROC symbol=GetProcAddress(lib, "my_plugin_function");
if(symbol)
{
int (*fnct)(int)=NULL;
memcpy(&fnct, &symbol, sizeof(fnct));
int result=fnct(123);
std::cout << "result=" << result << '\n';
}
FreeLibrary(lib);
}
std::cout << "~~~~ leaving " << __func__ << " ~~~~\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment