How to create an external character array in C?
I have tried various ways to define char cmdval[128]
but it always says undefined reference to 'cmdval'
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.
UPDATE:
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 :( "undefined reference to `cmdval'"
EDIT: 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
You need to declare it in the .h file
extern char cmdval[128];
And then define the value in first.c;
char cmdval[128];
Then anything that includes your .h file, provided it is linked with first.o will have access to it.
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.
Example:
global.h:
extern char cmdval[128];
first.c:
#include "global.h"
char cmdval[128];
int main() {
strcpy(cmdval, "testing");
test();
}
second.c:
#include "global.h"
void test() {
printf("%s\n", cmdval);
}
You can compile this using:
gcc first.c second.c -o main
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
Extern
doesn't mean find it somewhere, it changes the variable linkage
to external
, which means no matter how many time you declare a variable, it references to the same thing.
e.g. These references the same thing in c(not c++), a global variable's linkage by default is external
.
external char cmdval[128];
char cmdval[];
char cmdval[128];
The problem is that you shoud first compile them into .o, then link those .o together.
gcc -c first.c second.c
gcc -o first.o second.o
or
gcc first.c second.c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With