Skip to content

Instantly share code, notes, and snippets.

@chen3feng
Created March 21, 2024 03:20
Show Gist options
  • Save chen3feng/a6f20b4a90007d910b525e301665d6da to your computer and use it in GitHub Desktop.
Save chen3feng/a6f20b4a90007d910b525e301665d6da to your computer and use it in GitHub Desktop.
Weak symbol in MSVC
#include <stdio.h>
#define DEFINE_WEAK_VARIABLE(Type, Name) \
extern "C" Type Name; \
extern "C" Type Name##Default; \
__pragma(comment(linker, "/alternatename:" #Name "=" #Name "Default")) \
extern "C" Type Name##Default \
#define DEFINE_WEAK_FUNCTION(Type, Name, Params) \
extern "C" Type Name Params; \
extern "C" Type Name##Default Params; \
__pragma(comment(linker, "/alternatename:" #Name "=" #Name "Default")) \
extern "C" Type Name##Default Params\
DEFINE_WEAK_VARIABLE(const char*, WeakValue) = "hello";
DEFINE_WEAK_FUNCTION(void, error_log, ()) {}
// Uncomment to see string definition replace weak ones.
// const char* WeakValue = "world";
// void error_log() { printf("log\n"); }
int main() {
error_log();
printf("WeakValue=%s\n", WeakValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment