[英]Multiple definitions of … (linker error?)
我的代碼中出現某種編譯器/鏈接器錯誤,很可能與預處理器有關。 錯誤消息顯示為“ x的多個定義”,其中x是lib.c文件中4個函數中的任何一個。 我正在使用的編譯器/鏈接器是與code:blocks打包在一起的GNU GCC編譯器
我嘗試將#include的順序更改為不成功,這使我相信這是一個鏈接器錯誤,而不是編譯器錯誤,這是事實是,如果我犯了故意的語法錯誤,則編譯器會發現並中止而不給出錯誤消息。
感謝所有幫助/建議/批評,謝謝!
這是main.c文件:
#include <stdlib.h>
#include "lib.c"
int main()
{
getGradeAverage();
return EXIT_SUCCESS;
}
和lib.c:
#include "defs.h"
void getUserName ()
{
printf ("please enter the your name:");
studentRecord sr;
scanf("%40[^\n]%*c",&sr.studentName);
}
void getCourse (index)
{
printf("please enter the name of course 1:");
courseRecord cr1;
scanf("%40[^\n]%*c",&cr1.courseName);
do{
printf("please enter a grade for course 1:");
if ((scanf("%i",&cr1.grade))>-2)
{
printf("the grade you entered is not on the scale. please try again:");
fflush(stdin);
continue;
}
} while(true);
printf("please enter the name of course 2:");
courseRecord cr2;
scanf("%40[^\n]%*c",&cr2.courseName);
do{
printf("please enter a grade for course 1:");
if ((scanf("%i",&cr2.grade))>-2)
{
printf("the grade you entered is not on the scale. please try again:");
fflush(stdin);
continue;
}
} while(true);
}
void GPAPrint ()
{
int GPA;
studentRecord sr;
courseRecord cr1;
courseRecord cr2;
printf("Student name: %s\n",&sr.studentName);
}
void getGradeAverage ()
{
int index=1;
getUserName();
getCourse(index);
GPAPrint();
return (0);
}
defs.h文件在這里也很重要,因為它包含大多數#includes和structs。
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#define MAX_LENGTH 40
typedef struct courseRecord
{
char courseName [MAX_LENGTH+1];
int grade;
}courseRecord;
typedef struct studentRecord
{
char studentName [MAX_LENGTH+1];
char courseName[2];
}studentRecord;
大概您已在構建中包含lib.c
,並在main.c
#include
它。 這將使已編譯的對象(例如lib.o
和main.o
)每個都具有函數的定義。 鏈接器選擇了此方法(因為它檢查所有目標文件,而編譯器一次生成一個,因此無法檢測到兩個或多個目標文件定義了多個對象的實例),並抱怨多個定義。
原則上,請勿#include
.c
文件。
而是將函數的聲明(即原型)放在頭文件中(例如lib.h
)。
#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED
#include "defs.h"
void getUserName();
void getCourse (index);
// etc
#endif
和#include
在每個需要使用功能的.c
文件中。 這提供了足夠的信息,因此編譯器可以檢查您是否正確調用了函數。 然后將函數定義(即它們的實現)放在lib.c
。 lib.c
還需要#include "lib.h"
,因此(除其他事項外)編譯器可以檢查標頭中函數的聲明是否與定義匹配。
我還在標題中放置了包含衛兵。 我會把它留給您作為練習,讓Google找出原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.