C语言创建的extern char数组 [英] Create extern char array in C
问题描述
如何创建C的一个外部字符数组?
How to create an external character array in C?
我已经尝试了各种方法来定义字符cmdval [128]
,但它总是说未定义引用'cmdval
I have tried various ways to define char cmdval[128]
but it always says undefined reference to 'cmdval'
我想提出一个cmdval字符串中的 first.c
文件,并在其他使用 second.c
文件。我尝试添加了 global.h
文件的extern字符cmdval [128]
,但没有运气。
I want to put a string in cmdval in first.c
file and use it in other second.c
file. I tried adding a global.h
file with extern char cmdval[128]
but no luck.
更新:
global.h
extern char cmdval[128];
first.c
#include "global.h"
char cmdval[128];
function(){
strcpy(cmdval, "a string");
}
second.c
#include "global.h"
function(){
printf("%s \n",cmdval); //error
}
FAIL :(未定义参考`cmdval'
FAIL :( "undefined reference to `cmdval'"
编辑:
我在linux工作(编辑微型OS XV6然后编译和运行QEMU的话),我不知道这是否是一个障碍。
I am working in linux (editing a mini OS xv6 then compiling and running it in qemu), I don't know if it is a barrier
推荐答案
您需要声明它.h文件
extern char cmdval[128];
和再定义first.c的价值;
And then define the value in first.c;
char cmdval[128];
然后什么,包括您.h文件中,只要它与first.o链接将有机会获得它。
Then anything that includes your .h file, provided it is linked with first.o will have access to it.
要详细说明,外部的说法,还有一个外部变量,这将参考......如果你不然后声明cmdval地方,cmdval永远存在,且外部引用永远不会参考任何东西。
To elaborate, "extern" is saying, there is an external variable that this will reference... if you dont then declare cmdval somewhere, cmdval will never exist, and the extern reference will never reference anything.
例如:
global.h:
extern char cmdval[128];
first.c:
first.c:
#include "global.h"
char cmdval[128];
int main() {
strcpy(cmdval, "testing");
test();
}
second.c:
second.c:
#include "global.h"
void test() {
printf("%s\n", cmdval);
}
您可以编译这个使用:
gcc first.c second.c -o main
还是先.o文件并将其链接
Or make the .o files first and link them
gcc -c first.c -o first.o
gcc -c second.c -o second.o
gcc first.o second.o -o main
这篇关于C语言创建的extern char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!