[英]How to set up multiple C files to coexist
我如何設置一個結構,以便我有方法
helper.c
main.c中
main.h
...如何在main.c中包含helper.c並使用helper.c中內置的方法?
我正在運行makefile:
all:
gcc -o main main.c
gcc -o helper helper.c
clean:
rm -f main
rm -f helper
我知道我需要一個helper.h,但是如何正確設置呢...說我希望我的幫助文件看起來像這樣:
struct Node{
struct Node* nxt;
int x;
};
int isThere(struct Node *head, int value){
if(head==NULL){
return 0;
}
struct Node *tmp=head;
while(tmp!=NULL){
if(tmp->x==value){
return 1;
}
tmp=tmp->nxt;
}
return 0;
}
struct Node *nodeInsert(struct Node *head, int value){
if(head==NULL){
head=malloc(sizeof(struct Node));
head->x=value;
head->nxt=NULL;
printf("inserted\n");
return head;
} else if(head!=NULL && isThere(head,value)==1){
printf("duplicate\n");
return head;
} else{
struct Node *new;
struct Node *tmp=head;
while(tmp->nxt!=NULL){
tmp=tmp->nxt;
}
new=malloc(sizeof(struct Node));
new->x=value;
tmp->nxt=new;
new->nxt=NULL;
printf("inserted\n");
return head;
}}
我認為問題在於你錯過了在C中編譯和鏈接的理解。有很多來源可以解釋這個,這里有一個很好的解釋: http : //courses.cms.caltech.edu/cs11/material/c/mike /misc/compiling_c.html
你應該做的是將所有這些編譯成目標文件,然后將它們鏈接在一起。 你可以用單一命令做到這一點
gcc -o executable main.c helper.c
或先編譯每個,然后將它們鏈接在一起
gcc -c main.c gcc -c helper.c gcc -o executable main.o helper.o
確保在helper.h中為helper.c的所有函數編寫原型,並在main.c的開頭包含helper.h
gcc -o helper helper.c
會嘗試編譯和鏈接,但由於helper.c
沒有定義main()
,因此它不會鏈接。
你想要做的只是將main.c
和helper.c
分別編譯成目標文件:
gcc -c main.c #-o main.o (the -o main.o part is implied if missing)
gcc -c helper.c #-o helper.o
然后將生成的目標文件鏈接到最終的可執行文件中。
gcc -o main main.o helper.o
至於標題: helper.c
定義struct Node
和方法nodeInsert
和isThere
。 為了正確使用它們, main
需要它們的原型,所以提供它們的標准方法是定義一個helper.h
頭:
#ifndef HELPER_H
#define HELPER_H /*header guard to protect against double inclusion*/
struct Node{
struct Node* nxt;
int x;
};
int isThere(struct Node *head, int value);
struct Node *nodeInsert(struct Node *head, int value);
#endif
並將其包含在main.c
的頂部:
#include "helper.h"
//...
(您也可以將它包含在helper.c
。這應該允許編譯器幫助您捕獲可能的錯誤不一致。)
更改您的makefile,以便引用應該在二進制文件中的所有.c
文件:
all:
gcc -o main main.c helper.c
另外,你在main.c
的代碼需要知道helper.c
的方法聲明,這就是為什么struct聲明和helper.c
代碼的函數聲明應該在main.h
(或者在helper.h
並包含在內)在main.h
)
我想補充到@約翰·韋爾登的答案,你可以包括你的helper.c
在main.c
直接在聲明它的功能static
像這樣的例子:
// main.c
#include "helper.c"
int main(void)
{
HelloWorld();
return 0;
}
// helper.c
#include <stdio.h>
static void HelloWorld(void)
{
puts("Hello World!!!");
}
在你的Makefile中你可以編譯helper.c和main.c,如:
gcc -o main main.c helper.c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.