[英]Passing struct to a function gets 'undefined reference to' error
在与C进行练习时,我遇到了一个问题,希望堆栈溢出的人可以为我提供帮助。 后面的故事是我想对如何使用结构有深入的了解,因此我开始使用这个概念,但是当我开始使用数组并将结构传递给函数时遇到了一个问题。
在Linux中使用G ++编译代码时,出现编译错误:
/tmp/ccCjoSgv.o: In function `main':
main.c:(.text+0x10e): undefined reference to `indexBooks(int, book)'
collect2: error: ld returned 1 exit status
我花了几个小时试图自己解决类似的Stack Overflow问题,但仍然不明白为什么会出现此编译错误。 谁能提供他们的专业知识并解释为什么我会遇到这些错误?
book.h
struct book{
char title[100];
char author[100];
unsigned int bin;
};
主要包括
#include <stdio.h>
#include <stdlib.h>
#include "books.h"
主要原型
void askUsrNum(int*);
void indexBooks(int, struct book science);
内部main()
int usrNum;
struct book science[usrNum];
... plus the code below...
主要功能调用
askUsrNum(&usrNum); //ask user how many books to catalog
indexBooks(usrNum, *science); //record the books using struct
实际功能
void askUsrNum(int *usrNum){
printf("How many books are you cataloging: ");
scanf("%i", usrNum);
return;
}
void indexBooks(int usrNum, struct book science[]){
int i = 0;
int limit = (usrNum -1);
for(i = 0; i <= limit; i++){
printf("Book %i Title: ", i+1);
scanf("%s", science[i].title);
printf("Book %i Author: ", i+1);
scanf("%s", science[i].author);
printf("Book %i BIN: ", i+1);
scanf("%i", &science[i].bin);
printf("\n"); //newline
return;
}
}
您声明的原型与您的函数定义不匹配。 您在声明:
void indexBooks(int, struct book science);
但是您正在定义 :
void indexBooks(int usrNum, struct book science[])
注意定义中的括号。 您的声明声明了一个带有单个struct book
参数的函数,但定义带有一个struct book
数组 。 您应该将声明更改为void indexBooks(int usrNum, struct book science[])
。
您的函数原型和实现不匹配:
原型:
void indexBooks(int, struct book science); // science should be an array instead
实现方式:
void indexBooks(int usrNum, struct book science[])
看来您的原型是错误的, indexBooks()
正在采用结构数组而不是单个结构。
您应该首先尝试首先修复原型:
void indexBooks(int, struct book science[]);
同样在main
,您应该传递整个数组而不是其第一个元素:
indexBooks(usrNum, *science); //record the books using struct // incorrect
应该
indexBooks(usrNum, science);
原型和功能不匹配:
void indexBooks(int usrNum, struct book science);
void indexBooks(int usrNum, struct book science[]){
一个是数组,一个是结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.