Namespace problem in C ++

I have two files Sample.cpp and Main_file.cpp. Sample.cpp has only one namespace n1that contains a variable definition int x. I want to print this variable xin my main_file.cpp. How should I do it?

//Sample.cpp_BEGINS

namespace n1
{
    int x=10;
}
//Sample.cpp_ENDS

//Main_FILE_BEGINS

void main()
{
    print x;
}
//MAIN_FILE_ENDS

Thanks for any help you can provide.

+5
source share
4 answers

You use the full name of the variable:

int main()
{   
     n1::x = 10;

     return 0;
}
+6
source

To make n1::xaccessible from main.cpp, you probably want to create and enable sample.h:

// sample.h
#ifndef SAMPLE_H
#define SAMPLE_H

namespace n1
{
    extern int x;
}
#endif

// sample.cpp
#include "sample.h"

namespace n1
{
    int x = 42;
}

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

int main()
{   
     std::cout << "n1::x is " << n1::x;
}

If you prefer not to create a header file, you can also do this in your main.cpp:

#include <iostream>

namespace n1
{
    extern int x;
}    

int main()
{   
     std::cout << "n1::x is " << n1::x;
}
+5
source

using namespace n1 , , @als.

+4
source

From your comment, it seems that you want only 2 .cppfiles. In this case, the following work will be performed:

//Sample.cpp_BEGINS
namespace n1
{
  int x=10;
}
//Sample.cpp_ENDS

//Main_FILE_BEGINS
namespace n1
{
  extern int x;   // <---- mention that `x` is defined in other .cpp file
}
void main()
{
  print n1::x;  // to avoid 'n1::', mention 'using namespace n1;` above
}
//MAIN_FILE_ENDS
+3
source

All Articles