[英]linking files in c( multiple definition of…)
我正在嘗試在c中鏈接一些文件,並得到以下錯誤提示:“ createStudentList的多個定義”
我的main.c:
#include "students.h"
int main(void)
{
return 0;
}
students.h:
#ifndef _students_h_
#define _students_h_
#include "students.c"
bool createStudentList();
#endif
students.c:
#include <stdbool.h>
typedef struct Students
{
int id;
double average;
} Student;
bool createStudentList()
{
return true;
}
由於包含在內,您在main.o和student.o中都定義了函數createStudentList()
,這會導致您觀察到鏈接器錯誤。
我建議執行以下操作。 結構(類型)定義和函數原型應放入頭文件中:
#ifndef _students_h_
#define _students_h_
#include <stdbool.h>
typedef struct Students
{
int id;
double average;
} Student;
bool createStudentList(void);
#endif
以及源文件中的實際代碼,其中包括頭文件
#include "students.h"
bool createStudentList(void)
{
return true;
}
現在,通過包含students.h
您可以在其他源文件中使用類型和函數createStudentList
。
從students.h中刪除#include "students.c"
。 因此,定義發生了兩次-一個來自students.h,另一個來自students.c-因此發生了沖突。
只需刪除上面提到的行,然后在students.h中添加#include <stdbool.h>
。 進行這些修改,您的代碼將可以編譯和鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.