11

I get this /tmp/ccnL7Yz1.o: In function 'main': main.cpp:(.text+0x70): undefined reference to 'dng::genDungeon()' main.cpp:(.text+0xf0): undefined reference to 'dng::clrDungeon(char**)' collect2: error: ld returned 1 exit status error when I'm trying to compile my program. It worked great before I added namespace functions. I'm compiling it like this: g++ -std=c++11 main.cpp Dungeon.cpp

Dungeon.h

namespace dng {
    char** genDungeon();
    void clrDungeon(char**);

    class Dungeon {
    //Methods and variables
    }
}

Dungeon.cpp

#include "Dungeon.h"

using namespace dng;
char** genDungeon() 
{
    //Stuff
}
void clrDungeon(char** dungeon) 
{
    //Another Stuff
}
/*Implementation of class methods
void Dungeon::genStart(){} -> like this */

main.cpp

#include "Dungeon.h"

int main () 
{
    //Stuff
    auto dungeon = dng::genDungeon();
    //Stuff
    dng::clrDungeon(dungeon);
    return 0;
}

I also tried to make .o files by myself g++ -std=c++11 -c main.cpp g++ -std=c++11 -c Dungeon.cpp and then link them, but got the same error. What can be the problem?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • You could have searched a bit first: [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Emil Laine Aug 07 '15 at 18:44
  • 2
    I'm voting to reopen this. The original title smells of *duplicate*, but the question is really about a misunderstanding of `using namespace`. – Drew Dormann Aug 07 '15 at 18:50
  • @Борис Кот Такие вопросы лучше задавать на ru.stackoverflow.:) – Vlad from Moscow Aug 07 '15 at 18:52
  • @zenith I searched a lot but didn't find anything similar. And it seems like your link doesn't provide a solution for my problem. – Борис Кот Aug 07 '15 at 18:59

1 Answers1

12

Enclose the function definitions in the namespace dng where they are declared.

#include "Dungeon.h"

namespace dng
{
char** genDungeon() 
{
    //Stuff
}
void clrDungeon(char** dungeon) 
{
    //Another Stuff
}
//...
}

Or use qualified names.

include "Dungeon.h"

using namespace dng;

//...

char** dng::genDungeon() 
{
    //Stuff
}
void dng::clrDungeon(char** dungeon) 
{
    //Another Stuff
}

Otherwise, the functions are defined in the global namespace, and as a result, you declared four functions: two in the namespace dng and another two in the global namespace.

Wandering Fool
  • 2,170
  • 3
  • 18
  • 48
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335