あなたのコードはそのままで問題ありません。Cで複数のソースファイルを使用する方法の例を挙げて、あなたが書いたものと比較することができます.
main.c
とをsome_lib.c
含むが与えられた場合、 defined inの関数プロトタイプを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;
}
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);
}
これをコンパイルして実行すると、最初の例と同じ出力が生成されます。