The usage of extern in c++ -


i've having difficulty understanding how 'extern' works. i've searched google there doesn't seem particular example case i'm trying

if have file main.cpp references one.h , in have list named list1 (which double array of 100 x 100) have double list1[100][100];

how can use list in one.cpp please?

extern double list1[100][100] 

is not working :/

main.cpp:

#include "one.h"  extern double list1[100][100]; 

one.cpp:

void one::uselist() { for(j = 0; j < 100; j++)    {      for(i = 0; < 100; i++)     {          list1[j,i] = 0.5;     }  } } 

this have.

error i'm getting:

1>main.obj : error lnk2001: unresolved external symbol "double (* list1)[100]" (?list1@@3pay0ge@na)

a variable declaration @ namespace scope definition unless put extern on it; it's declaration.

an important rule in c++ can't have multiple definitions of objects same name. if header file contained double list1[100][100];, work long ever included in 1 translation unit. include header file in multiple translation units, have multiple definitions of list1. you've broken rule!

so have global variable accessible multiple translation units, need make sure there declaration in header file. extern:

extern double list1[100][100]; 

however, cannot include header , try use object because there isn't definition yet. list1 declaration says array of type exists somewhere, need define create object. in single translation unit (one of .cpp files usually), need put:

double list1[100][100]; 

now, each of .cpp files can include header file , ever declaration. it's fine have multiple declarations across program. one of .cpp files have definition.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -