[英]Undefined reference error while compiling
I'm trying to compile a project that has multiple *.c files and *.h file when I type the following command: 当我键入以下命令时,我正在尝试编译具有多个* .c文件和* .h文件的项目:
$gcc -c -I ../hdr main.c gestic.c menu.c
the hdr folder is where the *.h files are located, the .o files are created but when I try to link them using the command: hdr文件夹是* .h文件所在的位置,.o文件已创建,但是当我尝试使用以下命令链接它们时:
$gcc -o main.o gestic.o menu.o
I see errors 我看到错误
gestic.c:(.text+0x..): undefined reference to functions that are declared in *.h files
Try: 尝试:
$ gcc main.o gestic.o menu.o
-o filename: Place output in filename -o filename:将输出放置在filename中
$gcc -Wall -c -I../hdr -o main.o main.c
$gcc -Wall -c -I../hdr -o menu.o menu.c
$gcc -Wall -c -I../hdr -o gestic.o gestic.c
$gcc -Wall -o myprogram main.o menu.o gestic.o
Using a Makefile is very common for this task 使用Makefile在此任务中非常常见
example (untested) Makefile: 示例(未试用的)Makefile:
CC=gcc
CFLAGS=-Wall -I../hdr
all: myprogram
myprogram: main.o menu.o gestic.o
$(CC) -o $@ $^
gestic.o: gestic.c
$(CC) $(CFLAGS) -c -o $@ $<
main.o: main.c
$(CC) $(CFLAGS) -c -o $@ $<
menu.o: menu.c
$(CC) $(CFLAGS) -c -o $@ $<
Firstly header files are not included, secondly you might use the function that doesn't contain the definition. 首先,不包括头文件,其次,您可以使用不包含定义的函数。
The message undefined reference to 'function_name' implies that of all the object files you're giving to the linker, none of them has a definition for function_name. 消息中未定义的对“ function_name”的引用意味着您要提供给链接器的所有目标文件中,没有一个具有function_name的定义。 That means that either
这意味着
You're not linking with *.o *.c (as compiled) does not contain a definition for function_name -- by 'as compiled' I mean with all of the various preprocessor options you use on it. 您未与* .o * .c链接(编译时)不包含function_name的定义-通过“编译时”,我的意思是指您在其上使用的所有各种预处理程序选项。
here - Iinclude/
在这里
Iinclude/
try, 尝试,
gcc -c file.c -I<include_dir>
If you compile more files better to have makefile to create the objects of those files, link those objects along with header. 如果更好地编译更多文件以使makefile创建这些文件的对象,则将这些对象与标头一起链接。
Sample makefile, 样本makefile,
CC = gcc
CFLAGS = -Wall
INCLUDE = sample.h
OBJ = samople1.o sample2.o
%.o: %.c $(INCLUDE)
$(CC) $(CFLAGS) -c -o $@ $<
go: $(OBJ)
gcc $(CFLAGS) -o $@ $^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.