Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linker can't find function definition in a namespace

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?

like image 299
Борис Кот Avatar asked Aug 07 '15 18:08

Борис Кот


1 Answers

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.

like image 90
Vlad from Moscow Avatar answered Nov 15 '22 16:11

Vlad from Moscow