您的代码就目前而言很好。我可以给你一个例子,说明如何在 C 中使用多个源文件,你可以与你写的内容进行比较。
给定 amain.c
和some_lib.c
包含func
,您需要定义 a ,它定义了在 中定义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;
}
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);
}
编译并运行它将产生与第一个示例相同的输出。