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.
You use the fully qualified name of the variable:
int main()
{   
     n1::x = 10;
     return 0;
}
                        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;
}
                        add a line using namespace n1 in main or you can also do as @als suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With