C++ Preprocessor Variables
I went several years programming in C/C++ without really knowing about these preprocessor variables. They can be very useful for debugging and logging of custom run time errors/warnings. I have not found a definitive list of them, but here is a list of some useful ones that I know of. (The following variables can vary by compiler, but generally work)
| __LINE__ | Contains the current line number being processed. |
| __FILE__ | Contains the current file name (full path) being processed. |
| __DATE__ | Contains the compile date, This is the date that the file was compiled, not necessarily the current date. |
| __TIME__ | Contains the compile time. This is the time that the file was compiled, not necessarily the current time. |
| __TIMESTAMP__ | Contains the current date and time. This is the date and time that the file was compiled, not necessarily the current date and time. |
| __FUNCTION__ | Contains the function name. (this is part of C99, the new C standard. Not all C++ compilers support it) |
| __cplusplus | Defined when compiling a C++ program. In some older compilers, this is also called c_plusplus. |
| __STDC__ | Defined when compiling a C program, and may also be defined when compiling C++ |
Instead of explaining these variables, here is an example program that demonstrates how you may use some of them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> #define PUKE_TRACE(X,Y) puke_trace(__FUNCTION__, __FILE__, __LINE__, __threadid(), X, Y) void puke_trace(const char* func, const char* file, int line, unsigned long thread, const char* msg, std::ostream& os) { os << msg << " : Line " << line << ", file " << file << ", function " << func << ", thread " << thread << ".\n"; } int main(int argc, char* argv[]) { PUKE_TRACE("Test 1.",std::cout); PUKE_TRACE("Test 2.",std::cerr); PUKE_TRACE("Test 3.",std::clog); return 0; } |
The above program will output something like this:
Test 2. : Line 14, file /path/to/test.cpp, function main, thread 3712.
Test 3. : Line 15, file /path/to/test.cpp, function main, thread 3712.
__threadid() is not a preprocessor variable obviously, but it can be useful when tracing/debugging/logging multi-threaded applications, usually used in conjunction with preprocessor variables.
References:
http://www.codeguru.com/forum/showthread.php?t=231043
http://www.cppreference.com/preprocessor/preprocessor_vars.html
Did you sanitize your data input?