extern var inside a namespace
Dec 2, 2009 at 2:32pm UTC
I have these files:
::::::::::::::
command.h
::::::::::::::
1 2 3
namespace cmd {
extern const char * show;
}
::::::::::::::
command.cpp
::::::::::::::
1 2 3 4
#include <command.h>
using namespace cmd;
const char * show = "show" ;
::::::::::::::
main.cpp
::::::::::::::
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include "command.h"
using namespace std;
using namespace cmd;
int main()
{
cout << show << endl;
return 0;
}
But I got the error:
main.cpp:(.text+0x7): undefined reference to `cmd::show'
So I had to write command.cpp file like this:
1 2 3
#include <command.h>
const char * cmd::show = "show" ;
Why is not possible to use the
using namespace
diretive in command.cpp?
Dec 2, 2009 at 2:45pm UTC
No. using
can only be used to use the symbol, not to declare it or define it.
Dec 2, 2009 at 2:46pm UTC
Because when you define something, the compiler must know in which namespace you are defining it.
1 2
using namespace cmd;
const char * show = "show" ;
Will define
show
in the global namespace.
The
using namespace cmd
makes the compiler search stuff in the cmd namespace if those are not found in the global one but it works only when you need to use an already defined symbol.
when defining some stuff inside the namespace you should do something like this if you don't want to type too much:
1 2 3 4
namespace cmd
{
const char * show = "show" ;
}
Dec 2, 2009 at 3:12pm UTC
Sorry, but the answers do not convince me.
I've always used these types of things with classes and never found problems.
Look at this:
command.h
1 2 3 4 5 6 7 8 9
namespace cmd {
extern const char * show;
class Command {
public :
static const char * name;
void print();
};
}
command.cpp
1 2 3 4 5 6 7 8 9 10 11
#include <command.h>
const char * cmd::show = "show" ;
using namespace cmd;
const char * Command::name = "Command" ;
void Command::print() {
// ...
}
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include "command.h"
using namespace std;
using namespace cmd;
int main()
{
cout << show << endl;
cout << Command::name << endl;
Command myCommand;
myCommand.print();
return 0;
}
Dec 2, 2009 at 3:17pm UTC
On line 7 of command.cpp, the class Command has already been defined, which is why you can use it with using.
Dec 3, 2009 at 12:26am UTC
@ Tomas
That won't work.
command.cpp should look like this:
1 2 3 4 5 6 7 8 9 10 11 12
#include "command.h"
namespace cmd
{
const char * show = "show" ;
const char * Command::name = "Command" ;
void Command::print() {//...}
//.... Other stuff for the cmd namespace
}
Dec 3, 2009 at 8:31am UTC
guestgulkan, it works.
Topic archived. No new replies allowed.