2012-11-23 157 views
0

我試圖編譯在Xcode的一個簡單的程序,得到了以下消息:未定義內部鏈接和未定義的符號錯誤

function<anonymous namespace>::Initialize' has internal linkage but is not defined

function<anonymous namespace>::HandleBadInput' has internal linkage but is not defined

Undefined symbols for architecture x86_64: 
    "(anonymous namespace)::Initialize()", referenced from: 
     _main in main.o 
    "(anonymous namespace)::HandleBadInput()", referenced from: 
     _main in main.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

頭文件看起來是這樣的:

#ifndef WJKErrorHandling 
#define WJKErrorHandling 

namespace WJKErrorHandling{ 

    void Initialize(void); 
    int HandleBadInput(void); 

} 

#endif // defined(WJKErrorHandling) 

實施方式在文件看起來像這樣:

#include <iostream> 
#include "WJKErrorHandling.h" 

namespace WJKErrorHandling{ 

    void Initialize(void){ 

     std::cin.exceptions(std::cin.failbit); 
    } 

    int HandleBadInput(void){ 

     std::cerr << "Input Error: wrong type?\n"; 
     std::cin.clear(); 

     char BadInput[5]; 
     std::cin >> BadInput; 

     return 1; 
    } 

} 

和main.cpp中看起來是這樣的:

#include <iostream> 
#include "WJKErrorHandling.h" 


void Prompt (void){ 

    //Prompts the user to begin entering numbers 

    std::cout << "Begin entering numbers: \n"; 
} 

float GetNumber (void){ 

    std::cout << "Number: \n"; 
    float Number; 
    std::cin >> Number; 
    return Number; 
    } 

std::string GetString (void){ 

    std::cout << "String: \n"; 
    std::string String; 
    std::cin >> String; 
    return String; 

} 

int main() 
{ 
    Prompt(); 
    WJKErrorHandling::Initialize(); 

    int ReturnCode = 0; 

    try{ 

     float Number = GetNumber(); 
     std::cout << Number; 
     std::string String = GetString(); 
     std::cout << String; 

     std::cout << "SUCCESS!!!!\n"; 

    } 
    catch(...){ 

     ReturnCode = WJKErrorHandling::HandleBadInput(); 
    } 


    return ReturnCode; 
} 

我試圖找到答案,到目前爲止,但我不明白任何的帖子,我找到了。我是新的C++,所以任何幫助將不勝感激!

+0

你編譯過包含這些WJKErrorHandling函數的源文件嗎? – mathematician1975

回答

3

您的#define Guard導致名稱查找問題。

變化低於風格應該解決這個問題:

#ifndef WJK_ERROR_HANDLING_H 
#define WJK_ERROR_HANDLING_H 
+0

這工作!謝謝您的幫助! – wjkaufman

0

這原來是一個壞包括後衛:

#ifndef WJKErrorHandling 
#define WJKErrorHandling 

,因爲您稍後嘗試使用WJKErrorHandling爲命名空間,但宏使它消失。

更改您的包括後衛是這樣的:

#ifndef WJKERRORHANDLING_H 
#define WJKERRORHANDLING_H 

這可能是更地道並不太可能的東西相沖突。

1

根據它的wikipedia page,你也可以使用非標準的但更習慣的#pragma once它受到所有主要編譯器的支持。

由於許多編譯器都有優化來識別包括警衛,所以兩者之間沒有速度優勢。至於我自己,我看到的#pragma once以下優點:

  • 它只有一個含義(而定義的目的不同),並不會與其他的東西(例如一個命名空間爲你的情況)發生衝突。
  • 鍵入的內容很少,記住它很簡單。
  • 由於錯誤(WJKERRORHANDLNG_H,ups和我失蹤),因爲您將標題作爲另一個副本啓動並且忘記更改包含警衛,因此會給您帶來令人討厭的騷動會話,因此您不能有錯誤。