Create extern char array in C

后端 未结 4 761
春和景丽
春和景丽 2020-12-09 17:09

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 \'

相关标签:
4条回答
  • 2020-12-09 17:52

    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
    
    0 讨论(0)
  • 2020-12-09 17:54

    You should have a compilation unit in which you define the cmdval variable. The extern keyword only declares that the variable exists, it does not define it.

    Put the following line in first.c, second.c or in an other C file of your choice:

    char cmdval[128];
    
    0 讨论(0)
  • 2020-12-09 17:55

    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
    
    0 讨论(0)
  • 2020-12-09 18:02

    In second.c

    #include "global.h"
    

    define extern char cmdval[128] in global.h as well.

    0 讨论(0)
提交回复
热议问题