[英]C program Compilation error : reference to main
我是C編程新手,需要幫助解決編譯問題:
有3個.c文件(main.c,file1.c,file2.c),file1.c和file2.c僅包含在main.c中調用的函數定義。 當我嘗試使用以下命令編譯main.c文件時,出現以下錯誤:
gcc -Wall ./trigger-solve/main.c
_approx_help", referenced from:
_print_help in main-9e2c6e.o
"_approximate", referenced from:
_main in main-9e2c6e.o
"_free_matrix", referenced from:
_main in main-9e2c6e.o
"_print_matrix", referenced from:
_main in main-9e2c6e.o
"_read_matrix", referenced from:
_main in main-9e2c6e.o
"_read_sparse_matrix", referenced from:
_main in main-9e2c6e.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
但是,在閱讀了此錯誤后,我發現了發生的原因,因為file1.c和file2.c不包含main函數。 所以我在兩個文件中都添加了這個主要功能:
int main()
{
return 1;
}
在這一點上,當我編譯file1.c和file2.c時,它們不會給我錯誤,但是在運行main.c時,我仍然遇到相同的編譯錯誤。 我也不知道在編譯file1.c和file2.c之后如何將它們鏈接到main.c?
有人可以幫忙嗎?
您需要將所有翻譯單元鏈接在一起。 也許一次清洗,就像這樣:
gcc -Wall main.c file1.c file2.c
現在,您已經有了一個名為a.out
的可執行文件,可以隨時使用。
當然,每次更改一個文件時都無法重建整個項目 ,因此通常您需要分別編譯每個TU,然后在最后一步鏈接所有內容(並為輸出文件起一個更好的名稱):
gcc -Wall -c main.c
gcc -Wall -c file1.c
gcc -Wall -c file2.c
gcc -o myprog main.o file1.o file2.o
您是否對此進行了任何研究? 在線上有很多相關示例。
您不應在file1.c和file2.c中定義主要功能。 您應該使用-c選項編譯所有.c文件,然后將它們鏈接到main,如下所示:
gcc main.o file1.o file2.o
你可以
gcc -Wall *.c
將編譯當前目錄中的所有.c文件...這是一個很好的快捷方式,如果您將每個項目保存在單獨的文件夾中
基本上,您有鏈接錯誤。 請記住,任何程序只有一個main()函數。 在您的示例中,必須最終將此main()與其他文件鏈接以創建可執行文件。 main()是任何C程序的入口點。 因此,在源代碼中應該只有一個main()才能創建可執行文件。 對於您的情況,我會說使用Makefile進行編譯和鏈接。 Makefile節省了編譯時間,非常方便。
我會說-使用Makefile。 Makefile使工作更加輕松。 將來,如果您必須擴展功能,請添加一個新文件,並在makefile中添加一個新條目。 這是makefile的最簡單形式。
發出make-可執行文件名稱-應用后,將創建該應用。 接下來,運行./app
Makefile文件
target = file1.0 file2.o main.o
[tab] gcc file1.o file2.o main.o -o app
file1.o: file1.c
[tab] gcc -c file1.c -o file1.o
file2.o: file2.c
[tab] gcc -c file2.c -o file2.o
main.o: main.c
[tab] gcc -c main.c -o main.o
現在,運行Makefile。
$make target
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.