extern var inside a namespace

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?
No. using can only be used to use the symbol, not to declare it or define it.
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";
}

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;
}

On line 7 of command.cpp, the class Command has already been defined, which is why you can use it with using.
@ 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
}
guestgulkan, it works.
Topic archived. No new replies allowed.