array declared in header doesn't print anything

Hello,

I have declared a string array in a header and want to use it in other headers and functions. I used extern and it works for one the headers but for the other one, it is empty. Program runs and there are no error messages.

Any help would be appreciated.


1
2
// I defined it in this header.  For the example lets call this weapon.h
std::string weaponChoice[] {"bat", "pistol", "golf club", "rifle", "axe", "shovel", "knife", "tampons"};


I then put this in another header, lets say attack.h
 
 extern std::string weaponChoice[];


I can use the array in this attack.h like this
 
 std::cout << "# You hit him with " << weaponChoice[wC] << " and do " << weapon_damage << " damage!" << std::endl;


But I cannot use it in story.h
1
2
3
extern std::string weaponChoice[]; //This is what is in story.h



1
2
//It doesn't work in story.h.  Just prints out a blank.
 std::cout << "\t >> Enter '1' to attack zombie with " << weaponChoice[wC] << std::endl;


Does anyone know why it's not working?

Thanks in advance.


Last edited on
Why are you trying to use a global variable in the first place?

You shouldn't try to be defining the variable in two header files.

The first snippet should be in a source file and "extern" qualified declaration would be in the header file.

data.h
1
2
3
4
5
6
7
8
#ifndef DATA_H
#define DATA_H

#include <string>

extern std::string weaponChoice[];

#endif // DATA_H 


data.cpp
1
2
3
4
#include "data.h"

std::string weaponChoice[] {"bat", "pistol", "golf club", "rifle",
                            "axe", "shovel", "knife", "tampons"};


print_func.h
1
2
3
4
5
6
7
#ifndef PRINT_FUNC_H
#define PRINT_FUNC_H


void print();

#endif // PRINT_FUNC_H 


print_func.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "print_func.h"
#include "data.h"
#include <iostream>

void print()
{
    for(int i = 0; i < 8; i++)
    {
        std::cout << weaponChoice[i] << std::endl;
    }
}


main.cpp
1
2
3
4
5
6
7
8
#include "print_func.h"

int main()
{
    print();

    return 0;
}
Last edited on
What you have in your latest post should work. This assumes main.cpp, print_func.cpp and data.cpp have all been added to your project.

What to you mean by "it's not working"? Please be specific. Are you getting compile errors? Linker errors? Or??? Please post the EXACT error message.

// I defined it in this header. For the example lets call this weapon.h
 
std::string weaponChoice[] {"bat", "pistol", "golf club", "rifle", "axe", "shovel", "knife", "tampons"};

Do not initialize variables in a header file. As jlb said, that should be in a .cpp file (as you have in your subsequent post).

//It doesn't work in story.h. Just prints out a blank.
 
 std::cout << "\t >> Enter '1' to attack zombie with " << weaponChoice[wC] << std::endl;

Don't put executable code in a header file.


Last edited on
Topic archived. No new replies allowed.