在C中编译多个文件

标签 c gcc compilation makefile

我最近问了this question关于在 C 中编译多个文件,以便文件 main.c 可以引用文件 modules.c。答案最终是将模块文件制作成头文件并让 main 导入它。

我现在被告知这是一种不正确的方法,因为 C 支持模块化编译。我的 Makefile 在下面,这应该是正确的,但是我在 main.c 中收到每个函数调用的错误 -- warning: implicit declaration of function X

我需要做什么才能使用两个 .c 文件而不是 .c.h 文件正确编译它? main.c 文件有一个 main() 函数,需要能够调用 modules.c 中的函数。

生成文件:

#################################################################
# Variables
# -- allows C-source and assembly-source files mix. Again, the
# -- indented lines start with a TAB(^I) and not spaces..
#################################################################

CFLAGS  = -g -Wall -Werror
LDFLAGS =
CC      = gcc
LD      = gcc

TARG    = driver
OBJS    = modules.o main.o

#################################################################
# Rules for make
#################################################################

$(TARG): $(OBJS)
        $(LD) $(LDFLAGS) $(OBJS) -o $(TARG)

%.o: %.c %.s
        $(CC) $(CFLAGS) -c $<

clean:
        rm -f *.o *˜ $(TARG)

print:
        pr -l60 Makefile modules.c main.c | lpr

#################################################################
# Dependencies -- none in this program
#################################################################

最佳答案

您已经获得了有关使用 GCC 和 Makefile 的反馈,并且注意到完成任务的典型方法是两个 .c 文件和一个 .h 文件。但是,如果您使用函数声明(这可以说更简单,只是更难维护和有用),则不需要 .h 文件,如下例所示。

主.c:

void moduleFunc1(int); // extern keyword required for vars, not for functions

int main()
{
    moduleFunc1(100);

    return 0;
}

模块.c:

#include <stdio.h>

void moduleFunc1(int value)
{
    printf("%d\n", value);
}

编译:

gcc main.c module.c

编辑:在查看了您链接的作业之后,我最好的猜测实际上仍然是您正在寻找的是函数声明。引用作业中的“其他”#7:

A function should be declared in the module/function where
it is called and not in global scope. Say A calls B and C does
not call it then B should be declared in A only.

在我的示例中,函数声明位于调用它的模块中,并且似乎符合 A-B-C 示例。 (令人困惑的部分是全局范围注释,但我不会说函数声明的范围是全局的。观察一下,如果你将声明移到 main() 下面,例如,它会把事情搞砸。我还没有找到任何东西不过,这一点严格权威。)

关于在C中编译多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18815399/

相关文章:

c++ - 在 if-else if 链中使用 Likely()/Unlikely() 预处理器宏

php - 为 MediaWiki Math 编译 Texvc

java - 如何在 Java 6 中使用为 Java 7 编译的库?

c - 使文件在所有节点上可用

java - 从方法返回 "void"或 "null"

c - 我的程序在 C 中反转字符串有什么问题?

c++ - 不要在 GCC 中使用 -O3 标志优化特定循环

gcc - C - 如何使用 GCC SSE 向量扩展访问向量元素

c++ - 除非使用 cout,否则代码不会执行

c - 关于中断?