【问题标题】:I'm getting a linkage error [duplicate]我收到链接错误[重复]
【发布时间】:2017-11-24 11:33:53
【问题描述】:

我已针对类似问题应用了您提供的所有解决方案,但我仍然收到此错误:

 undefined reference to `setgolf(golf&, char*, int)'
collect2: error: ld returned 1 exit status

这里是代码头

#ifndef SANS_H_INCLUDED
#define SANS_H_INCLUDED
const int len = 40;
struct golf 
{
    char fullname[len];
    int handicap;
};

//void setgolf(golf &,char * ,int);
int setgolf(golf &);
void sethandicap(golf &,int );
void showgolf(const golf &);    
#endif

这是包含函数定义的文件

#include <iostream>
#include <cstring>
#include "chapter9exe3.h"
void setgolf(golf & s,char *c ,int hc)    
{    
    strcpy(s.fullname,c);
    s.handicap=hc;
}

int setgolf(golf & s)    
{    
    std::cin.getline(s.fullname,len);
    if(s.fullname[0] == '\0'&& s.fullname[1] == '\0' && s.fullname[2] == '\0')    
    return 0;   
    else
    return 1;
}

void sethandicap(golf & s,int n )
{
    s.handicap = n;    
}

void showgolf(const golf & s)
{
    std::cout<<"the full name :"<<s.fullname<<std::endl;
    std::cout<<"the handcape  :"<<s.handicap<<std::endl;    
}

这里是包含主函数的文件

#include <iostream>
#include "sans.h"
int main()
{    
    golf player;
    char name[len] = "santers God's men";
    int handicap = 84;
    setgolf(player,name,handicap);
    return 0;
}

【问题讨论】:

  • 您在标题中声明了函数int setgolf(golf &amp;);,但是您随后定义了2个版本,1个参数和3个参数,因此首先存在不匹配加上3个参数版本被注释掉
  • 我投票决定将此作为题外话关闭,因为这只是一个简单的印刷错误:将基本代码注释掉。

标签: c++ function file compiler-errors


【解决方案1】:

取消注释:

//void setgolf(golf &,char * ,int);

在你的头文件中,因为你在 main:

setgolf(player,name,handicap);

它将在头文件中搜索匹配的原型,并且无法找到它,因为您已对其进行了注释。

也就是说,你用三个参数调用函数,但在头文件中只提供了这个函数的原型,只有一个参数。结果,对setgolf()的三个参数的引用肯定是未定义的!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    相关资源
    最近更新 更多