0

I want to compile my C++ code locally. I have separated it into header files (.hpp) and code files (.cpp)

galaxy.hpp

#pragma once
#include <vector>
namespace Edge
{
    namespace Galaxy
    {

        class Galaxy
        {
        public:
            std::vector<int> GalaxyFunction();
        };
    }
}

galaxy.cpp

#include "galaxy.hpp"
#include <vector>
namespace Edge
{
    namespace Galaxy
    {

        std::vector<int> Galaxy::GalaxyFunction()
        {
            std::vector<int> d = {1, 23, 5};
            return d;
        }

    }
}

main.cpp

#include "galaxy.hpp"
#include "iostream"
int main()
{

    Edge::Galaxy::Galaxy ser;
    auto a = ser.GalaxyFunction();
    std::cout << a.size();

    return 0;
}

The code compiles on online compiler for eg here . But when I try to compile it locally I get error:

PS A:\C++Pr\sometype> cd "a:\C++Pr\sometype\" ; if ($?) { g++ main.cpp -o main } ; if ($?) { .\main }
c:/program files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\senor\AppData\Local\Temp\ccjwwRcg.o:main.cpp:(.text+0x1c): undefined 
reference to `Edge::Galaxy::Galaxy::GalaxyFunction()'
collect2.exe: error: ld returned 1 exit status

Can someone please suggest me what is causing this problem and how should I fixed it. Thanks.

  • 2
    `g++ main.cpp -o main`: This is compiling only the `main.cpp` file. You should list all `.cpp` files there, not only `main.cpp`, i.e. `g++ main.cpp galaxy.cpp -o main` – user17732522 Nov 17 '22 at 08:13
  • unrelated: when you include in your header, you don't need to include a second time in you cpp. Also reconsider giving your class the same name as your namespace to avoid confusion. – nick Nov 17 '22 at 08:17

0 Answers0