How do you declare a global std::vector 2d array across multiple files? c++

c++, extern, header, multidimensional-array, vector

Solution

Like this:

header.h:

#ifndef HEADERS_H_DECLARED
#define HEADERS_H_DECLARED

#include <vector>

extern std::vector<std::vector<int>> A;

#endif

A.cpp:

#include "header.h"

std::vector<std::vector<int>> A(10, std::vector<int>(10));

Make sure to spell the names of your files correctly.

Problem

I have a header file in which there is a 2d array extern declaration, and a cpp file in which there is the actual definition for the array for it to link to. I would like to replace this array with a 2d vector, but my compiler keeps telling me: ``` 'A': redefinition; multiple initialization ``` Here is my code header.h ``` #ifndef HEADERS_H_DECLARED #define HEADERS_H_DECLARED #include <vector> ... extern std::vector<std::vector<int>> A(10, std::vector<int>(10)); ... #endif ``` A.cpp ``` #include "headers.h" ... std::vector<std::vector<int>> A(10, std::vector<int>(10)); ... ``` Then in all my other .cpp files I use this vector. When It was an array it all worked fine, I assume it has something to do with my syntax for declaring a 2 dimensional vector across multiple files but I have no idea!

Original source