Create extern char array in C

SMUsamaShah picture SMUsamaShah · Oct 6, 2011 · Viewed 67.4k times · Source

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

Answer

Geoffrey picture Geoffrey · Oct 6, 2011

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