use*_*565 0 c global-variables
假设我有一个全局变量
char Dir[80]; /* declared and defined in file1.c but not exported using extern etc */
Run Code Online (Sandbox Code Playgroud)
Dir 变量是运行时在程序的 main() 中创建的目录的名称。在这个文件中,我们操作这个变量并将它传递给在 file2.c 中定义的函数 func 这个 Dir 变量是一个目录,所有函数都在其中创建各自的日志。
而不是将这个变量 n 次传递给最终调用 func() 的每个函数。我将其设为全局。
func(x,Dir); /* x is a local variable in a function */
Run Code Online (Sandbox Code Playgroud)
/* 现在在 file2.c */
void func(int x,char *Dir)
{
/*use this variable Dir */
}
Run Code Online (Sandbox Code Playgroud)
我们这里接收到的 Dir 的值与 file1.c 中的值不一样。为什么 ?编译器:Windows 上的 gcc
你的代码很好。我可以给你一个例子,说明在 C 中应该如何使用多个源文件,你可以与你编写的内容进行比较。
给定一个main.c与一个some_lib.c包含func,需要定义一个some_lib.h定义的函数原型func中所定义some_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;
}
Run Code Online (Sandbox Code Playgroud)
some_lib.c(包含 )的定义func:
#include "some_lib.h"
void func(int x, char * dir)
{
printf("Received %d and %s\n", x, dir);
}
Run Code Online (Sandbox Code Playgroud)
some_lib.h(包含 的导出函数的函数原型/声明some_lib.c):
#ifndef SOME_LIB_H
#define SOME_LIB_H
#include <stdio.h>
void func(int x, char * dir);
#endif
Run Code Online (Sandbox Code Playgroud)
然后上面应该编译为:
gcc main.c some_lib.c -o main
Run Code Online (Sandbox Code Playgroud)
这将产生:
Received 100 and some_string
Run Code Online (Sandbox Code Playgroud)
但是,如果您确实在使用全局变量,则根本不需要传递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;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
some_lib.c 然后可以像使用范围一样使用全局定义的变量:
#include "some_lib.h"
void func(int x)
{
printf("Received %d and %s\n", x, dir);
}
Run Code Online (Sandbox Code Playgroud)
编译并运行它会产生与第一个示例相同的输出。