Code snippets

Hold states of various things
typedef enum { ITEM1, ITEM2, ITEM3, ITEM4,

ITEM_SIZE } ITEMS;

This will create an enumeration with 4 items excluding the size constant. Now we can declare an array with a size equal to the nr of items in the enum. If we want to change the state of item4 just do fred[ITEM4]=true;. An example of where this is useful: We read keyboard input and set KEY_Q to true when Q is pressed and to false when it is released. This way we can run function barney as long as KEY_Q is true. Need another key? Just add that to the enumeration, whereever you want. It won't interfere with earlier keys. And you could do like this with anything, ints, char* or even classes. Need to set the default values of the array? Just iterate through it, for (int i=0;ibaz, quux);

This is useful if you want to pack data into a struct and not just fill the struct with pointers. As the data is packed tighter this might increase performance (cache misses etc). It's also easier when saving/loading because not pointers has to be handled.

Creating a dynamic library with GCC

 * 1) include "mylib.h"

/** * My useless function */ int tux(int a,int b){ return (a+b)/(b-a); }

This is going to be our library. It has one simple function, tux, which takes to integer parameters and just does some random math with them. It includes a header, mylib.h, which isn't shown here because it just contains the prototype. But remember that the header is just as important as the code itself since we will only be able to call the functions that has its prototypes there. Unless we know about them and writes our own prototypes.

g++ -fPIC -c dynamic_libary.cpp g++ -shared -o libTest.so dynamic_libary.o

When compiling the library we use the -fPIC argument. This will generate the position-independent code needed when using a library. When we link our code we use the argument -shared to create a shared dynamic library. Well, thats it. It isn't any harder than that. I suggest you now copy your header to /usr/include and the libary to /usr/lib. Remember that if the library name is Barney, the file should be named libBarney.so.

/* we can use <> */ using namespace std;
 * 1) include            /* Since the header is */
 * 2) include          /* located in /usr/include */

int main(int argc,char* argv[]){

cout << tux(5,10) << endl;

return 0; }

To use the library just include the header with the prototypes and we can use the function. When linking just include the argument -lTest.