[英]How to use “extern struct” to share variables in c programming and compile with gcc?
我希望應該在源文件main.c和second.c之間訪問一些共享變量,而我的頭文件是all.h定義了共享數據類型,
#ifndef ALL_H
#define ALL_H
struct foo {
double v;
int i;
};
struct bar {
double x;
double y;
};
#endif
main.c在下面給出
/* TEST*/
#include "all.h"
#include "second.h"
int main(int argc, char* argv[])
{
struct foo fo; // should be accessed in second.c
fo.v= 1.1;
fo.i = 12;
struct bar ba; // should be accessed in second.c
ba.x= 2.1;
ba.y= 2.2;
sec(); // function defined in second.c
return 0;
}
second.h在下面給出
#include <stdio.h>
#include "all.h"
int sec();
second.c在下面給出
#include "second.h"
extern struct foo fo;
extern struct bar ba;
int sec()
{
printf("OK is %f\n", fo.v+ba.x);
return 0;
}
我以為我擁有所有聲明,並包含標題。 但是當我編譯
gcc -o main main.c second.c
or
gcc -c second.c
gcc -c main.c
gcc -o main main.o second.o
它將給出一些錯誤,例如
second.o: In function `sec':
second.c:(.text+0x8): undefined reference to `fo'
second.c:(.text+0xe): undefined reference to `ba'
collect2: ld returned 1 exit status
我認為使用extern
某個地方有誤,或者我錯誤地使用了gcc
?
問題出在范圍上。 您的變量( fo
& ba
)具有局部作用域,因為它們在main
中聲明。因此,它們的可見性僅限於main
函數中。 請使它們成為全局變量,它應該起作用。
錯誤消息表明鏈接器無法找到fo
和ba
。 使用extern
聲明,您已經告訴編譯器變量將存在於其他翻譯單元中,但不存在。
您需要將struct foo fo;
移到struct foo fo;
和struct bar ba;
在main()
函數之外。 現在,它們是函數局部變量。 它們必須是全局變量才能起作用。
//main.h
typedef struct
{
double v;
int i;
}foo;
//extern.h
extern foo fo;
//main.c
#include "main.h"
#include "extern.h"
//use fo.v here
//second.c
#include "second.h"
#include "main.h"
#include "extern.h"
foo fo;
//use fo.v here
只需在要使用fo的所有.c文件中包括#include“ main.h”,#include“ extern.h”。 請注意,foo fo僅位於second.c中,除此之外沒有其他地方
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.