Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 508
Tyson Klein Avatar asked May 07 '17 19:05

Tyson Klein


1 Answers

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.

like image 175
Kerrek SB Avatar answered Oct 27 '22 15:10

Kerrek SB