Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a namespace define in another `.cpp` file

Tags:

c++

I have this and I can't seem to include the namespace correctly.

main.cpp

#include <iostream>

int main()
{
    my_space::Print(); // main.cpp:5:5: error: use of undeclared identifier 'my_space'

    return 0;
}

otherclass.cpp

#include <iostream>

namespace  my_space {
    int x, y;

    void Print()
    {
        std::cout << "Hello from namespace my_space." << std::endl;
    }
}

I have tried adding a otherclass.h with namespace my_space {}; in it and in main.cpp include #include "otherclass.h" but this didn't worked either.

like image 573
cara ash Avatar asked Apr 17 '26 13:04

cara ash


2 Answers

You need to split up the declaration from the definition.

Your declaration looks like this:

namespace my_space {
  void Print();
}

Your definition looks like this:

#include <iostream>
#include "my_space.h"

void my_space::Print() {
    std::cout << "Hello from namespace my_space." << std::endl;
}

Then you add #include "my_space.h" to your main file so it knows about the declaration. The linker will take care of combining the final executable.

Things like x and y need more clarification as having random global variables laying around is asking for trouble.

like image 129
tadman Avatar answered Apr 20 '26 03:04

tadman


Leave your otherclass.cpp file as it is. Looks good.

Make a new otherclass.h file as you said you did, but make it look like this:

#pragma once

namespace my_space {
    void Print();
}

Then build it like this (if using GCC):

gcc -O2 -W -Wall -std=c++17 main.cpp otherclass.cpp -o testprogram

It is important to NOT get into the habit of writing all of your function code in the header file. Instead learn to hide everything that you can. Notice that in my example I didn't include your x and y variables. If those aren't needed by any other part of your program then no one else needs to know about them.

Code in header files adds compile time to every file that includes it. Worse, that code probably requires more header files to support it. Which have to be included and compiled for every cpp file that includes the first header.

This can lead to atrocities where 500 source files each rebuild half of Boost and include Windows.h for no good reason.

like image 36
Zan Lynx Avatar answered Apr 20 '26 02:04

Zan Lynx