win32 before main example

main
Allen Webster 2024-04-24 06:31:59 -07:00
parent 03d19e104d
commit 81ab0a3bbd
3 changed files with 44 additions and 3 deletions

View File

@ -0,0 +1,15 @@
@echo off
REM: Path setup
SET src=%cd%
cd ..
if not exist "build\" mkdir build
cd build
REM: Build
cl /nologo /GL /O2 %src%\win32_before_main.c

View File

@ -0,0 +1,24 @@
// this specific section contains before-main function pointers
// this pragma ensures the compilation unit will generate this section
#pragma section(".CRT$XCU", read)
// declare the "before main" function
static void run_before_main_func(void);
// set the before-main execution function pointer
__declspec(allocate(".CRT$XCU"))
__pragma(comment(linker, "/INCLUDE:run_before_main_ptr"))
void (*run_before_main_ptr)(void) = run_before_main_func;
// define the "before main" function
int x = 0;
static void run_before_main_func(void){
x = 100;
}
// main
#include <stdio.h>
int main(){
printf("x = %d\n", x);
return(0);
}

View File

@ -31,9 +31,11 @@
# pragma section(".CRT$XCU", read)
# define BEFORE_MAIN(n) extern void n(void); \
__declspec(allocate(".CRT$XCU")) void (*n##__)(void) = n; \
__pragma(comment(linker, "/include:" #n)) extern void n(void)
# define BEFORE_MAIN(n) static void n(void); \
__declspec(allocate(".CRT$XCU")) \
__pragma(comment(linker, "/INCLUDE:" #n "__")) \
void (*n##__)(void) = n; \
static void n(void)
#elif OS_LINUX