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で複数のソースファイルを使用する方法の例を挙げて、あなたが書いたものと比較することができます.

main.cとをsome_lib.c含むが与えられた場合、 defined inの関数プロトタイプをfunc定義する を定義する必要があります。some_lib.hfuncsome_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 に答える