⬅ Previous Next ➡

Namespaces & Preprocessor

Namespaces & Preprocessor in C++
  • Namespace is used to avoid name conflicts by grouping identifiers (variables, functions, classes).
  • The most common namespace is std (Standard Library).
  • Preprocessor runs before compilation and handles directives like #include, #define, and conditional compilation.

1) Namespaces (Why and How)

  • Namespace prevents clashes when two libraries have same function/variable name.
  • Syntax:
    • namespace Name { ... }
    • Access using Name::member
#include <iostream>
using namespace std;

namespace First {
    void show() {
        cout << "First namespace" << endl;
    }
}

namespace Second {
    void show() {
        cout << "Second namespace" << endl;
    }
}

int main() {
    First::show();
    Second::show();
    return 0;
}

2) std Namespace

  • std contains standard classes and functions (cout, cin, string, vector, etc.).
  • Ways to use std:
    • std::cout, std::cin (recommended)
    • using namespace std; (easy but can cause name conflicts)
    • using std::cout; (limited import)
#include <iostream>

int main() {
    std::cout << "Hello C++" << std::endl;
    return 0;
}
#include <iostream>
using std::cout;
using std::endl;

int main() {
    cout << "Limited using example" << endl;
    return 0;
}

3) Macros (#define)

  • Macros are replaced before compilation (no type checking).
  • Use for constants and small expressions (but prefer const in C++).
#include <iostream>
using namespace std;

#define PI 3.14159
#define SQUARE(x) ((x) * (x))

int main() {
    cout << "PI = " << PI << endl;
    cout << "Square(5) = " << SQUARE(5) << endl;
    return 0;
}

4) Preprocessor Directives

  • #include: include header file
  • #define: define macro
  • #undef: remove macro
  • #ifdef / #ifndef: check macro defined or not
  • #if / #elif / #else / #endif: conditional compilation

5) Header Inclusion

  • <iostream> is a system header (use < >).
  • "myheader.h" is a user-defined header (use quotes).
#include <iostream>  // system header
#include "mylib.h"   // user header (example)

int main() {
    return 0;
}

6) Conditional Compilation

  • Used to enable/disable code (debug mode, platform-specific code).
#include <iostream>
using namespace std;

#define DEBUG 1

int main() {

#if DEBUG
    cout << "Debug mode ON" << endl;
#else
    cout << "Debug mode OFF" << endl;
#endif

    return 0;
}

7) Include Guards (Header Protection)

  • Prevents multiple inclusion of the same header file.
// mylib.h
#ifndef MYLIB_H
#define MYLIB_H

int add(int a, int b);

#endif

8) Quick Notes

  • Namespaces avoid name conflicts: use Name::member.
  • std is the standard namespace (cout, cin, string, vector).
  • Macros are preprocessor replacements; prefer const/inline in modern C++.
  • Conditional compilation helps in debug and platform-specific code.
⬅ Previous Next ➡