// Allocates RWX memory of given size and returns a pointer to it. On failure, // prints out the error and returns NULL. void* alloc_executable_memory(size_tsize){ void* ptr = mmap(0, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (ptr == (void*)-1) { perror("mmap"); returnNULL; } return ptr; }
// As used in the linux kernel. // A macro that expands to 1 if a preprocessor value // was defined to 1, and 0 if it was not defined or // defined to an other value.
// Not really special, but so useful I thought // I'll put it here. Can also be used with other // libraries (OpenAL, OpenSLES, ...) #ifdef DEBUG # define GL(line) do { \ line; \ assert(glGetError() == GL_NO_ERROR); \ } while(0) #else # define GL(line) line #endif
// Put GL around all your opengl calls: GL(glClear(GL_COLORS_MASK)); GL(pos_loc = glGetAttribLocation(prog, "pos"));
Array size macro
這個也不世新玩意了
1 2 3 4 5 6 7 8 9 10 11
// Is there any C project that does not use it? #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
// Can be used like this: int a[] = {0, 4, 5, 6}; int n = ARRAY_SIZE(a); // n = 4
// Warning: does not work with array arguments to functions: intfunc(int a[]){ int nb = ARRAY_SIZE(a); // Would not work! }
// I use this one all the time when writing // video game. One of the reason why I // don't like to use C++.
// Let say we have this struct structobj { constchar *name; float pos[2]; float color[4]; };
// We can write a macro like this one #define OBJ(_name, ...) \ (struct obj) { \ .name = _name, \ .color = {1, 1, 1, 1}, \ __VA_ARGS__ \ };
// Now we can use the macro to create new objects. // This one with color defaulted to {1, 1, 1, 1}. structobjo1 = OBJ("o1", .pos = {0, 10}); // This one with pos defaulted to {0, 0}. structobjo2 = OBJ("o2", .color = {1, 0, 0, 1});
X macros
即使在C++當中,這也是個非常重要的技巧之一,利用Macro來進行Code Generation。 X Macro分成兩部分,一個是彼此相相關連的List,另外一個是巨集,對這個List進行展開動作,而這點Template無能為力。 例如
1 2 3 4 5 6 7 8 9 10 11
#define COLORS \ X(Cred, "red") \ X(Cblue, "blue") \ X(Cgreen, "green") #define X(a, b) a, enum Color { COLORS }; #undef X #define X(a, b) b, staticchar *ColorStrings[] = { COLORS }; #undef X