C:头文件和include问题。需要帮忙!

标签 c gcc makefile header-files

据我了解,C 具有 makefile 和 include 语句,因此您没有单一的怪物大小的文件,并且您应该在功能上分解您的代码。因此,如果我是对的,我应该能够跨 .c 文件进行功能调用,前提是我正确地执行了 header 和 make。

我正在尝试这样做,但不幸的是我遇到了错误。

文件内容如下:

文件 1)test.c:

#include<stdio.h>
#include"suc.h" 

main()
{
    printf("Hello World\n\n");
    printf("This is the number: %d \n\n", suc(6));
}

文件2)makefile:

CC=gcc
CFLAGS=-c -Wall

test: suc.o
$(CC) -Wall -o test test.c

suc.o: suc.c
$(CC) $(CFLAGS) suc.c

文件 3)suc.h

#ifndef SUC_H_GUARD

#define SUC_H_GUARD

// returns the successor of i (i+1)
int suc(int i);


#endif

文件 4)suc.c

#include "suc.h"

int suc(int i)
{
return i + 1;
}

当我制作 (make -B) 顶部时,我得到:

gcc -c -Wall suc.c
gcc -Wall -o test test.c
test.c:7: warning: return type defaults to 'int'
/tmp/cc/7w7qCJ.o: In function 'main':
test.c: (.text+0x1d): undefined reference to 'suc'
collect2: ld returned 1 exit status
make: *** [test] Error 1

但是: 两者都产生预期的结果: A) 这个单文件程序工作正常!

#include<stdio.h>

main()
{
    printf("Hello World\n\n");
printf("This is the number: %d \n\n", suc(6));
}

int suc(int i)
{
return i + 1;
}

B) 原始文件中的所有文件,但对 test.c 进行了以下更改:

#include<stdio.h>
#include"suc.h" //suc() is still defined b/c suc.h is included

main()
{
    printf("Hello World\n\n");
printf("This is the number: %d \n\n", 4); //HERE! -> no function call
}

求助,谢谢! 我不太明白错误消息试图告诉我什么。

最佳答案

您需要分别将源文件编译成它们的目标文件,然后链接目标文件以获得可执行文件test .

所以你需要:

CC=gcc
CFLAGS=-c -Wall

test: test.o suc.o
<tab>$(CC) -Wall -o test test.o suc.o

test.o: test.c
<tab>$(CC) $(CFLAGS) test.c

suc.o: suc.c
<tab>$(CC) $(CFLAGS) suc.c

哪里<tab>是一个选项卡。


您当前的 makefile 中的问题在于:

test: suc.o
    $(CC) -Wall -o test test.c

上面写着 test取决于 suc.o并获得 test你需要做的:

$(CC) -Wall -o test test.c

但查看编译/链接行,它不包含任何具有 suc 的源文件/目标文件函数定义。

您可以添加 suc.o作为:

$(CC) -Wall -o test test.c suc.o

但它被认为是不好的,因为说你只改变了 suc.c文件,那么您的 makefile 将重新生成 suc.o并且还必须重新生成test , 但用于再生 test你正在重新编译 test.c 甚至认为它没有改变。

关于C:头文件和include问题。需要帮忙!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4778156/

相关文章:

c++ - 如何在Makefile中对两组文件使用不同的规则?

c - 允许用户在 c 中再次启动程序?

c++ - Redis命令ERR:参数数量不正确hiredis

c - FFTW3 2D,传递 fftw_complex 数组

c - 数字及其对数作为编译常量而不手动更改两者?

bash - makefile 中的多行 bash 命令

c - 将字符串传递给函数的存储位置

配置: error: C compiler cannot create executables (macOS: Big Sur)

c - 如何在ubuntu上编译doom?

c++ - make/gmake 的条件依赖