#include is a C (and C style) preprocessor statement. It doesn't have to be at the top of your code (but that's just being anal, because it usually is). One important thing to note is that it doesn't define the libraries the code uses; it simply inserts the contents of the given file into the part of the file where the #include statement resides (from the compiler's point of view anyway). Coincidentally, the libraries you wish to use are linked with your code by the linker, not the compiler; header files just define or prototype functions exported by these libraries. Some of the most ingenius hacks submitted to the IOCCC rely in various strange #includes.

I would like to add that besides IOCCC tricks, #include can be handy in evading some of the C++'s flaws. For example, the default preprocessor does not allow double-evaluating things or iterate stuff; however, if you #include something, that'll help. Allow me to demonstrate:

I wanted to make a system for autogeneration of classes, so that class creator tells me what are his variables and then I can automatically construct a class that has get- and set- functions for those variables, plus init() (NOT creator-function, this was special init()), save(), load() and such functions that can do some interesting stuff for those variables. Now, because C++ doesn't allow the _code_ to examine the _types_ and _names_ of variables defined, I needed to work around this... this is how I made it:

First, class creator writes three files:

  • Variable definition file. This file has series of call to macros, like:
  • Class header file. There he makes some #defines (the class name, its parent and the name of variable definition file) and #includes "template.hh".
  • Class source. There he has those defines made earlier and includes "template.cc".

Now, this template.hh header... first, it defines the class by classname #defined earlier. Then, it needs to make the member variable-, get- and set-function definitions. Because the preprocessor does not have any sort of iteration (and thus is not programming language)... it #defines CLASSVAR (see, the macro "called" in VAR file) to INBODY, a predefined macro that is defined about like this:

#define INBODY(type,name) type it##name;\
const type& get##name() const { return it##name; }\
void set##name(const type& _t) { it##name=_t; }

This produces the desired code. In similar fashion, all the places that need to "iterate" through variable list (such as, in this case, init() -function which fills in an entry in array with information about this variable, its address inside the class and type), will just need to #define their own CLASSVAR and #include VAR!

Yay, I know it sounds terribly clumsy, but AFAIK this is the only way to do this. If you can make up a better one, let me know. Anyhow, this demonstrates the magic of #include.

Log in or register to write something here or to contact authors.