未定义内部链接和未定义的符号错误

问题描述:

我试图编译在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

您的#define Guard导致名称查找问题。

变化低于风格应该解决这个问题:

#ifndef WJK_ERROR_HANDLING_H 
#define WJK_ERROR_HANDLING_H 
+0

这工作!谢谢您的帮助! – wjkaufman

这原来是一个坏包括后卫:

#ifndef WJKErrorHandling 
#define WJKErrorHandling 

,因为您稍后尝试使用WJKErrorHandling为命名空间,但宏使它消失。

更改您的包括后卫是这样的:

#ifndef WJKERRORHANDLING_H 
#define WJKERRORHANDLING_H 

这可能是更地道并不太可能的东西相冲突。

根据它的wikipedia page,你也可以使用非标准的但更习惯的#pragma once它受到所有主要编译器的支持。

由于许多编译器都有优化来识别包括警卫,所以两者之间没有速度优势。至于我自己,我看到的#pragma once以下优点:

  • 它只有一个含义(而定义的目的不同),并不会与其他的东西(例如一个命名空间为你的情况)发生冲突。
  • 键入的内容很少,记住它很简单。
  • 由于错误(WJKERRORHANDLNG_H,ups和我失踪),因为您将标题作为另一个副本启动并且忘记更改包含警卫,因此会给您带来令人讨厌的骚动会话,因此您不能有错误。