[C/C++] main 함수앞에서 실행하기

spring·2020년 11월 9일
0

C++ 에서는 아주 쉽다.

전역 클래스 생성자를 사용하면 된다.

#include<iostream>
#if defined(_MSC_VER)
__declspec(selectany)
#elif defined(__GNUC__)
__attribute__((weak))
#endif
class premain {
public:
	premain() {
		std::cout << "premain" << std::endl;
	}
}_premain;
int main() {
	std::cout << "main" << std::endl;
	return 0;
}

C 에서는 다른 방법을 사용한다.

#include<stdio.h>
int
#if defined(__GNUC__)
__attribute__((constructor))
#endif
premain(void) {
	puts("premain");
	return 0;
}
#if defined(_MSC_VER)
# pragma section(".CRT$XCU",read)
__declspec(allocate(".CRT$XCU"))static int(*p)(void) = premain;
# pragma data_seg()
#endif
int main() {
	puts("hello, world");
	return 0;
}
profile
Researcher & Developer @ NAVER Corp | Designer @ HONGIK Univ.

0개의 댓글