MACRO and namespace in C++ ( and some coding style )

I have not used namespace in C++.
I know why namespace is necessary. However, I don’t want to introduce complexity in my projects and well-written codes don’t need to resolve symbol conflict with namespace.

Namespace can serve well when 3rd party libraries you can’t modify induce symbol conflict.

However, namespace doesn’t resolve conflict of multiple definition of same MACRO.

As you know, it is because MACRO is processed by preprocessor while namespace, structures, classes and so on are processed by compiler.

See how Xcode 3.2.1 presents warning for redefined MACRO

So, in the case of MACRO, header files should be prepared carefully.

This topic is very basic. However, this should be kept in mind. When you prepare your codes as a library, it is good practice to embrace your classes, structures and other data types exposed to outside of your library with namespace.

Also, this is again very basic.
Please do not put definition of methods and functions in header files. Source files which include your header file which contains definition of functions and method can introduce symbol conflict more or make building it without problems difficult. Why? Definition of functions and methods tend to have reference to other classes and structures. Then you need to also include header files for them in your header file. Including header files other than what are really necessary can make resolving compiling error very difficult. If a header file is included by 3 header files chained serially, and there are multiple incidents like that, it can introduce cyclic reference, or even though it is not cyclic, it can make things more difficult to figure out what symbol is included when by which.
Use forward declaration instead of including a header file.
For example,

class MyClass;

is better than

#include “MyClass”

in a header file which refers MyClass.
Also in such case, prefer this style.

class MyClass;

class SomeInfo {

    int m_Num;
    MyClass *m_Class;

If you use this style, then you should include the header file for “MyClass”

class SomeInfo {

    int m_Num;
    MyClass m_Class;

The difference is whether to use a pointer type or declare things statically.
If a class is declared statically, a compiler needs to know more detailed information about the class when it is declared. So, it requires the header file of the class.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: