Created
March 21, 2024 03:20
-
-
Save chen3feng/a6f20b4a90007d910b525e301665d6da to your computer and use it in GitHub Desktop.
Weak symbol in MSVC
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 <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
Ref:
You can also use __declspec(selectany).