Skip to content

Instantly share code, notes, and snippets.

@GTANAdam
Created April 5, 2021 11:58
Show Gist options
  • Select an option

  • Save GTANAdam/161761d131f24b8d94fd68619865cb77 to your computer and use it in GitHub Desktop.

Select an option

Save GTANAdam/161761d131f24b8d94fd68619865cb77 to your computer and use it in GitHub Desktop.
Keep unused exported functions from being stripped by linker, useful for linking static libraries that have unused exported functions targeted for C# P/Invoke marshaling or misc purposes
#pragma once
// LINKER_INCLUDE_UNUSED: Forces linker to keep unused functions that were declared elsewhere
// LINKER_KEEP_UNUSED: Forces linker to keep unused functions that are delcared within the current file
#define EXPORT extern "C" _declspec(dllexport)
#if defined(LINKER_INCLUDE_UNUSED)
#if defined(_WIN64)
#define LINKER_KEEP(s) EXPORT __pragma(comment (linker, "/export:"#s))
#elif defined(_WIN32)
#define LINKER_KEEP(s) EXPORT __pragma(comment (linker, "/export:_"#s))
#endif
#elif defined(LINKER_KEEP_UNUSED)
#if defined(_WIN64)
#define LINKER_KEEP(s) EXPORT __pragma(comment (linker, "/include:"#s))
#elif defined(_WIN32)
#define LINKER_KEEP(s) EXPORT __pragma(comment (linker, "/include:_"#s))
#endif
#endif
#define EXPORT_KEEP(RET, NAME, ...) LINKER_KEEP(NAME) RET NAME(__VA_ARGS__)
#include <cstdio> // printf
#define LINKER_KEEP_UNUSED
#include "export.h"
EXPORT_KEEP(void, myFn1);
void myFn1() {
printf("HELLO!\n");
}
EXPORT_KEEP(void, myFn2, int);
void myFn2(int a) {
printf("NUMBER: %d\n", a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment