Thursday 26 July 2012

Creating Libraries (namespaces)

Creating Libraries (namespaces)



Libraries usually come in the form of a header and an object (.o) file. To use them, #include "header.h" and link the .o file using g++. If the .o was compiled in C rather than C++, then indicate this with extern "C" {} to turn off name mangling. C++ encodes or "mangles" overloaded function names to allow them to be linked, but C does not since it doesn't allow overloading. extern "C" { // Turn off name mangling
#include "header.h" // Written in C
}
When writing your own library, use a unique namespace name to prevent conflicts with other libraries. A namespace may span multiple files. Types, objects, and functions declared in a namespace N must be prefixed with N:: when used outside the namespace, or there must be a using namespace N; in the current scope.
Also, to guard against possible multiple inclusions of the header file, #define some symbol and test for it with #ifndef ... #endif on the first and last lines. Don't have a using namespace std;, since the user may not want std visible.
#ifndef MYLIB_H // mylib.h, or use #if !defined(MYLIB_H)
#define MYLIB_H
#include <string>
// No using statement
namespace mylib {
class B {
public:
std::string f(); // No code
}
}
#endif

// mylib.cpp, becomes mylib.o
#include <string>
#include "mylib.h"
using namespace std; // OK
namespace mylib {
string B::f() {return "hi";}
}
#define could be used to create constants through text substitution, but it is better to use const to allow type checking. #define X Y has the effect of replacing symbol X with arbitrary text Y before compiling, equivalent to the g++ option -DX=Y. Each compiler usually defines a different set of symbols, which can be tested with #if, #ifdef, #ifndef, #elsif, #else, and #endif. #ifdef unix // Defined by most UNIX compilers
// ...
#else
// ...
#endif
Preprocessor statements are one line (no semicolon). They perform text substitutions in the source code prior to compiling. #include <header> // Standard header
#include "header.h" // Include header file from current directory
#define X Y // Replace X with Y in source code
#define f(a,b) a##b // Replace f(1,2) with 12
#define X \ // Continue a # statement on next line
#ifdef X // True if X is #defined
#ifndef X // False if X is #defined
#if !defined(X) // Same
#else // Optional after #if...
#endif // Required

No comments:

Post a Comment