Thread: extern Global array in seperate .h file

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    84

    extern Global array in seperate .h file

    Hi,

    I'm trying to use a global array declared in a .h file. The array is marked as static and defined in the .cpp file.

    I have a macro which gets the size of the array and is defined as such

    Code:
    #define sizeof_array(x) (sizeof(x)/sizeof(*x))
    but when I try to use this function in the code below I get the following error :

    Code:
    bool contains(string,string[],int);
    bool isArithemetic(string first) { return contains(first,cmd_arm,sizeof_array(cmd_arm));
    Code:
    error C2070: 'std::string []': illegal sizeof operand
    This only happens if i declare it as extern, however if I dont, I get a linker error static multiply defined symbols. Here is my header and cpp containing the array -
    Code:
    //commands.h
    #ifdef DEFINE_GLOBALS
    #define GLOBAL
    #else // !DEFINE_GLOBALS
    #define GLOBAL extern
    #endif
    
    #define sizeof_array(x) (sizeof(x)/sizeof(*x))
    
    #include <string>
    using namespace std;
    
    GLOBAL string cmd_arm[];// = { "+", "-" , "*" ,"/" , "sin", "cos","sqrt" };
    Code:
    //commands.cpp
    #define DEFINE_GLOBALS
    #include "Command.h"
    
    string cmd_arm[]  = { "+", "-" , "*" ,"/" , "sin", "cos","sqrt" };
    Does anyone know how I can fix this ? or a better way to have a global array ? thanks!

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I suppose you might need to specify the size of the array: GLOBAL string cmd_arr[7]. Alternatively I think the array might also be declared static and defined in the header.

    Code:
    #define sizeof_array(x) (sizeof(x)/sizeof(*x))
    I suppose a much better alternative is:

    Code:
    template <class T, unsigned N>
    unsigned sizeof_array(const T (&)[N])
    {
         return N;
    }
    Unlike the macro, this will fail to compile if your array has decayed to a pointer, instead of falsely reporting sizeof(T*) / sizeof(T) - be that 0, 1, 2, 4 or other.
    Last edited by anon; 09-30-2009 at 08:09 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. From a file into an array.
    By fmsguy06 in forum C Programming
    Replies: 20
    Last Post: 11-09-2008, 09:30 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  4. #include header files or .cpp files?
    By DoctorX in forum C++ Programming
    Replies: 3
    Last Post: 12-23-2006, 12:21 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM