c++: object declaration in header file

Ask a question
2

I have these files with the following content

a.hpp

#include <vector>

std::vector<int> vi;

a.cpp

#include "a.hpp"

void f() 
{
   for(auto x : vi) 
   {   
       std::cout << x << " ";
   }   
}

main.cpp

#include "a.hpp"

#include <iostream>
#include <vector>

int main()
{
   vi.push_back(21);
   std::cout << vi[0] << std::endl;

   return 0;
}

And I receive this error

/tmp/ccR9GhOw.o:(.bss+0x0): multiple definition of `vi'
/tmp/ccbkMhRw.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

What is the mistake I have made ?

Coin iconoffer bounty
add comment

0 Answer

Your Answer