Last active
April 4, 2020 22:42
-
-
Save mertyildiran/36eec5df78f3bfacfa970cd67506dcdf to your computer and use it in GitHub Desktop.
Mingw-w64 C dynamic linking with circular calls (without two way linkage)
This file contains hidden or 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
| gcc -Wl,--export-all-symbols main.c -o prog.exe | |
| gcc -shared -fPIC lib.c -o lib.o | |
| gcc -c -DBUILDING_LIB lib.c | |
| gcc -shared -o lib.dll lib.o -Wl,--out-implib,lib.a |
This file contains hidden or 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> | |
| #include "main.h" | |
| #ifdef BUILDING_LIB | |
| #define LIB __declspec(dllexport) | |
| #else | |
| #define LIB __declspec(dllimport) | |
| #endif | |
| int LIB library_function(void (*f)()) | |
| { | |
| printf("Hello from library!\n"); | |
| f(); | |
| /* unexported_callback(); */ /*< This one will not be exported in the second case */ | |
| return 0; | |
| } |
This file contains hidden or 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> | |
| #include <windows.h> | |
| void exported_callback() /*< Function we want to export */ | |
| { | |
| printf("Hello from callback!\n"); | |
| } | |
| void unexported_callback() /*< Function we don't want to export */ | |
| { | |
| printf("Hello from unexported callback!\n"); | |
| } | |
| typedef long long int (*lib_func)(); | |
| int call_library() | |
| { | |
| void *handle = NULL; | |
| lib_func func = NULL; | |
| handle = LoadLibraryW(L"./lib.dll"); | |
| func = GetProcAddress(handle, "library_function"); | |
| if (func == NULL) { | |
| fprintf(stderr, "Unable to get symbol\n"); | |
| return -1; | |
| } | |
| func(exported_callback); | |
| return 0; | |
| } | |
| int main(int argc, const char *argv[]) | |
| { | |
| printf("Hello from main!\n"); | |
| call_library(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment