你的代碼是好的,因爲它代表。我可以給你一個例子,說明如何在C中使用多個源文件,並且可以與你寫的內容進行比較。
給定一個main.c
和含有func
,需要定義一個some_lib.h
其限定在some_lib.c
定義的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);
}
編譯和運行,這將產生輸出作爲與第一實施例相同。
這可能是不同的,因爲你期待'Dir2'而不是'Dir'? –
@MikeKwan這是一個複製粘貼錯誤,但我已經糾正它 – user1437565
那麼代碼本身就很好。你能展示一個能夠再現你的問題的最小例子嗎? –