2011-08-16 155 views
1

这似乎是我的两个文件,userinterface.h链接未定义的符号错误

#ifndef USERINTERFACE_H 
#define USERINTERFACE_H 

#include <string> 
#include "vocabcollection.h" 

namespace user_interface 
{ 
//Finds a file 
// 
//Returns when user selects a file 
std::string findFile(); 

//more comments followed by functions 
} 

#endif 

和userinterface.cpp,

#include "userinterface.h" 
using namespace std; 
using namespace user_interface; 

string findFile() 
{ 
    return "./"; 
} 

//more placeholder implementations of such functions; void functions have nothing within 
//the brackets 

是给我从链接错误,这个转换:

Undefined symbols for architecture x86_64: 
make: Leaving directory `longdirectorypath' 
    "user_interface::showTestResults(int, int)", referenced from: 
     vocabCollection::test()  in vocabcollection.o 
    "user_interface::get(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)", referenced from: 
     addNewCollection()  in mainlogic.o 
     loadNewCollection()  in mainlogic.o 
    "user_interface::findFile()", referenced from: 
     loadNewCollection()  in mainlogic.o 
    "user_interface::displayMainMenu(std::vector<vocabCollection, std::allocator<vocabCollection> >)", referenced from: 
     mainlogic() in mainlogic.o 
    "user_interface::getUserAction()", referenced from: 
     mainlogic() in mainlogic.o 
ld: symbol(s) not found for architecture x86_64 
collect2: ld returned 1 exit status 
make: *** [cheapassVocab.app/Contents/MacOS/cheapassVocab] Error 1 
The process "/usr/bin/make" exited with code 2. 
Error while building project cheapassVocab (target: Desktop) 
When executing build step 'Make' 

这里发生了什么?

回答

4

在头文件中,在名称空间user_interface中声明函数findFile。在cpp文件中定义了自由函数findFile。是的,你是using namespace user_interface,但编译器不知道定义的findFile属于namespace user_interface。所有这些的结果是,您宣布user_interface::findFile并且定义了::findFile。当您拨打user_interface::findFile时,链接器找不到它,因为只有免费功能findFile

迎刃而解 - CPP文件:

#include "userinterface.h" 
using namespace std; 

namespace user_interface 
{ 
    string findFile() 
    { 
     return "./"; 
    } 
} 
2

你不能实现这样的findFile;它真的有在命名空间中去:

namespace user_interface 
{ 
    string findFile() 
    { 
     return "./"; 
    } 
} 

or: 

string user_interface::findFile() 
{ 
    return "./"; 
} 

using指令仅用于查询,而不是定义 - 想象一下using namespace std;会做所有的函数定义,否则!

1

您正在将findFile定义在错误的名称空间中。

要么

std::string user_interface::findFile() 
{ 
    return "./"; 
} 

namespace user_interface 
{ 
    std::string findFile() 
    { 
     return "./"; 
    } 
} 

using不影响这里的名字被定义,它不仅影响名称如何抬起头来。