Skip to content

Instantly share code, notes, and snippets.

@garettbass
Last active June 23, 2020 20:28
Show Gist options
  • Save garettbass/b624f2cca037da7c6c263d538b4a1749 to your computer and use it in GitHub Desktop.
Save garettbass/b624f2cca037da7c6c263d538b4a1749 to your computer and use it in GitHub Desktop.
Enumerating section symbols with clang/gcc (https://repl.it/@garettbass/clangsections)
#include <stdio.h>
#define CONCAT(A, B) _CONCAT(A, B)
#define _CONCAT(A, B) A##B
#define TOSTRING(...) _TOSTRING(__VA_ARGS__)
#define _TOSTRING(...) #__VA_ARGS__
#ifdef SECTION_DEFINITIONS
#define _section_declaration_definition(SECTION) section_definition(SECTION)
#else
#define _section_declaration_definition(SECTION)
#endif
#define section_declaration(SECTION)\
void* CONCAT(SECTION,_begin)(void);\
void* CONCAT(SECTION,_end)(void);\
_section_declaration_definition(SECTION)\
/**/
#define section_definition(SECTION)\
void* CONCAT(SECTION,_begin)(void) {\
extern void* CONCAT(__start_,SECTION);\
return &CONCAT(__start_,SECTION);\
}\
void* CONCAT(SECTION,_end)(void) {\
extern void* CONCAT(__stop_,SECTION);\
return &CONCAT(__stop_,SECTION);\
}\
/**/
#define section_entry(SECTION)\
__attribute((__section__(TOSTRING(SECTION))))
section_declaration(mysection) // declaration may appear more than once
section_definition(mysection) // definition must appear only once, defines endpoints
void print_mysection_entries(void)
{
const void** const end = mysection_end();
for (const void** itr = mysection_begin(); itr < end; ++itr)
{
const void* str = *itr;
if (str)
printf("%p : \"%s\"\n", itr, (char*)str);
else
printf("%p : null\n", itr);
}
}
int main(void)
{
section_entry(mysection)
static const char* mysection_0 = "mysection_0";
section_entry(mysection)
static const char* mysection_1 = "mysection_1";
section_entry(mysection)
static const char* mysection_2 = "mysection_2";
print_mysection_entries();
puts("DONE");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment