0

假设我有一个全局变量

 char  Dir[80];  /* declared and defined in file1.c  but not exported using extern etc */

Dir 变量是在运行时在程序的 main() 中创建的目录的名称。在这个文件中,我们操作这个变量并将它传递给在 file2.c 中定义的函数 func 这个 Dir 变量是一个目录,所有函数都在其中创建各自的日志。

而不是将此变量 n 次传递给最终调用 func() 的每个函数。我将其设为全局。

func(x,Dir); /* x is a  local variable in a function  */

/* 现在在 file2.c */

void func(int x,char *Dir)
{
   /*use this variable Dir */
}

我们这里收到的 Dir 的值和 file1.c 中的不一样。为什么 ?编译器:Windows 上的 gcc

4

1 回答 1

6

您的代码就目前而言很好。我可以给你一个例子,说明如何在 C 中使用多个源文件,你可以与你写的内容进行比较。

给定 amain.csome_lib.c包含func,您需要定义 a ,它定义了在 中定义some_lib.h的函数原型。funcsome_lib.c

main.c

#include <stdlib.h>
#include <stdio.h>
#include "some_lib.h"
/*
 * This means main.c can expect the functions exported in some_lib.h
 * to be exposed by some source it will later be linked against.
 */

int main(void)
{
    char dir[] = "some_string";

    func(100, dir);
    return EXIT_SUCCESS;
}

some_lib.c(包含 的定义func):

#include "some_lib.h"

void func(int x, char * dir)
{
    printf("Received %d and %s\n", x, dir);
}

some_lib.h(包含函数原型/导出函数的声明some_lib.c):

#ifndef SOME_LIB_H
#define SOME_LIB_H
#include <stdio.h>

void func(int x, char * dir);

#endif

上面的内容应该编译为:

gcc main.c some_lib.c -o main

这将产生:

Received 100 and some_string

但是,如果您确实使用的是全局变量,则根本不需要传递dir。考虑这个修改main.c

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

char dir[] = "some_string";

int main(void)
{
    func(100);
    return EXIT_SUCCESS;
}

dir在这里定义并且可以全局访问/定义。我们需要做的就是确保它some_lib.c知道它的存在。然后,链接器可以在链接阶段解析此符号。some_lib.h需要这样定义:

#ifndef SOME_LIB_H
#define SOME_LIB_H
#include <stdio.h>

/*
 * The extern informs the compiler that there is a variable of type char array which
 * is defined somewhere elsewhere but it doesn't know where. The linker will
 * match this with the actual definition in main.c in the linking stage.
 */
extern char dir[];
void func(int x);

#endif

some_lib.c然后可以像使用范围一样使用全局定义的变量:

#include "some_lib.h"

void func(int x)
{
    printf("Received %d and %s\n", x, dir);
}

编译并运行它将产生与第一个示例相同的输出。

于 2012-06-05T14:30:38.747 回答