在C中包含头文件时,它是否会自动包含同名的.c文件?

Dou*_*ith 7 c header

我在网上以及在我的教科书中环顾四周,这让我感到困惑.

假设你在stack.c中有一些堆栈函数,你将它们的原型放在stack.h中.您的主程序,例如test.c #include "stack.h"位于顶部.这就是所有示例的显示方式.

所以它包括原型,但它是如何实现的?头文件似乎不需要你#include stack.c使用它们.它只是搜索同一文件夹中的所有.c文件并尝试找到它们吗?

Jon*_*ler 9

没有; 它只包括标题.

您单独编译源代码,并将其与使用它的代码链接.

例如(玩具代码):

stack.h

extern int pop(void);
extern void push(int value);
Run Code Online (Sandbox Code Playgroud)

stack.c

#include "stack.h"
#include <stdio.h>
#include <stdlib.h>

enum { MAX_STACK = 20 };
static int stack[MAX_STACK];
static int stkptr = 0;

static void err_exit(const char *str)
{
     fprintf(stderr, "%s\n", str);
     exit(1);
}

int pop(void)
{
    if (stkptr > 0)
        return stack[--stkptr];
    else
        err_exit("Pop on empty stack");
}

int push(int value)
{
    if (stkptr < MAX_STACK)
        stack[stkptr++] = value;
    else
        err_exit("Stack overflow");
}
Run Code Online (Sandbox Code Playgroud)

test.c的

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

int main(void)
{
    for (int i = 0; i < 10; i++)
        push(i * 10);

    for (int i = 0; i < 10; i++)
        printf("Popped %d\n", pop());
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

汇编

c99 -c stack.c
c99 -c test.c
c99 -o test_stack test.o stack.o
Run Code Online (Sandbox Code Playgroud)

要么:

c99 -o test_stack test.c stack.c
Run Code Online (Sandbox Code Playgroud)

因此,您编译源文件(可选地生成目标文件)并链接它们.通常,stack.o文件将放入库(标准C库除外)中,并且您将链接到该库.当然,这也是标准C库函数所发生的情况.C编译器自动将C库(通常-lc)添加到链接命令.