Created
April 21, 2024 19:32
-
-
Save dogukanarat/4966bfc76c1e70210cb7a52c70cf6252 to your computer and use it in GitHub Desktop.
Module init with section attributes
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 <iostream> | |
#define REGISTER_MODULE(module_name) InitializeFunction init_module_##module_name __attribute__((used, section("__DATA,__MODULEINIT"))) = module_name; | |
typedef void (*InitializeFunction)(void); | |
void module1(void) | |
{ | |
std::cout << "module1 init..." << std::endl; | |
} | |
void module2(void) | |
{ | |
std::cout << "module2 init..." << std::endl; | |
} | |
REGISTER_MODULE(module1); | |
REGISTER_MODULE(module2); | |
extern void* __start_MODULEINIT __asm("section$start$__DATA$__MODULEINIT"); | |
extern void* __stop_MODULEINIT __asm("section$end$__DATA$__MODULEINIT"); | |
void init_all_modules() | |
{ | |
size_t count = ((size_t)&__stop_MODULEINIT - (size_t)&__start_MODULEINIT) / sizeof(InitializeFunction); | |
InitializeFunction* ptr_module = (InitializeFunction*)&__start_MODULEINIT; | |
for (size_t i = 0; i < count; ++i) | |
{ | |
(*ptr_module)(); | |
++ptr_module; | |
} | |
} | |
int main(int argc, char** argv) | |
{ | |
(void)argc; | |
(void)argv; | |
init_all_modules(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment