グローバル変数を定義する部分でよく分からないエラーが出まして、
ご説明をお願いしたいと思い書き込みしています。
実際にこのエラーで行き詰まっているのは別のプログラムなのですが、
似た構造の短いコードで同様のエラーが再現できましたので
そちらを掲載したいと思います。
環境はRed Hat Linux 7.2のgcc 2.95.3でコンパイルしています。
def.h#ifndef INIT_DEFINE
#define INIT_DEFINE
typedef double D;
D init(void);
#endif
test.h#include "def.h"
extern D aaa;
void test(void);
test.c#include <stdio.h>
#include "test.h"
#include "def.h"
D aaa;
aaa = init();
void test(void){
printf("%f", aaa);
}
コンパイル時のエラーメッセージ% gcc -c test.c -Wall
test.c:7: warning: type defaults to `int' in declaration of `aaa'
test.c:7: conflicting types for `aaa'
test.c:5: previous declaration of `aaa'
test.c:7: initializer element is not constant
test.c:7: warning: data definition has no type or storage class
test.c: In function `test':
test.c:10: warning: double format, different type arg (arg 2)
%
私の意図としてはtest.hでD型の変数aaaがextern宣言され、
test.cの5行目で変数aaaが定義され、7行目でD型の値を返すinit()によって
値が代入されるという流れなのですが、
コンパイル時のエラーによるとtest.cの5行目が定義とみなされておらず、
7行目が定義であるかのように思われているようです。
ちなみに、関数test()の内部にaaa=init();を移すと
何のエラーも出ずにコンパイルできますが、
関数test()は別の関数から何度も呼ばれ、aaaの値を保持したいので
test()の内部でaaaの初期化init()を行うのではなく外部で初期化を
行いたいと思っています。
何故このようなことが起こるのかご説明いただけませんでしょうか?
|