Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace issue in C++

Tags:

c++

namespaces

I have two files Sample.cpp and Main_file.cpp. Sample.cpp has only one namespace n1 which contains the definition of int variable x. I want to print this variable x in my main_file.cpp. How do I go about doing this?

//Sample.cpp_BEGINS

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

//Main_FILE_BEGINS

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

Thank you for any help you can provide.

like image 794
Jatin Avatar asked Jan 25 '12 06:01

Jatin


3 Answers

You use the fully qualified name of the variable:

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

     return 0;
}
like image 192
Alok Save Avatar answered Nov 15 '22 05:11

Alok Save


To make n1::x accessible from main.cpp you'll probably want to create and include 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;
}
like image 20
greatwolf Avatar answered Nov 15 '22 05:11

greatwolf


add a line using namespace n1 in main or you can also do as @als suggested.

like image 4
Vijay Avatar answered Nov 15 '22 05:11

Vijay