Home > Blockchain >  Undefined reference to class from namespace in C
Undefined reference to class from namespace in C

Time:12-03

I'm new to C and trying to do a small quant project with paper trading.

I have a header file alpaca/client.h as follows:

#pragma once

#include <iostream>
#include <../utils/httplib.h> 
#include <config.h>

using namespace std;

namespace alpaca {
    
        class Client {

            private:

                alpaca::Config* config;

            public:

                Client();
                string connect();
        };
}

The implementation in alpaca/client.cpp is

#include <iostream>
#include <string>
#include <client.h>
#include <httplib.h>

using namespace std;

namespace alpaca {

    Client::Client() {
        config = &alpaca::Config();
    };

    string Client::connect()  {
        httplib::Client client(config->get_url(MARKET));
        auto res = client.Get("/v2/account");
        if (res) {
            return res->body;
        }
        else {
            return "Error in Client::get_account(): "   to_string(res->status);
        }
    };
}

And my main.cpp is:

#include <iostream>
#include <string>
#include <client.h>

using namespace std;

int main()
{
    alpaca::Client client = alpaca::Client();

    client.connect();

    return 0;
}

However, I see the following error when I try to compile with g :

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\shubh\AppData\Local\Temp\cc765kwL.o:main.cpp:(.text 0x1ca): undefined reference to 'alpaca::Client::Client()'

Could anyone help with what exactly I'm missing? I'm not too sure.

The g command I use is g -I./src/alpaca src/main.cpp

CodePudding user response:

It looks like you forgot to compile the client.cpp file. The error message is saying that the linker cannot find a definition for the Client class constructor.

Try compiling both main.cpp and client.cpp with the g command, like this:

g   -I./src/alpaca  src/main.cpp src/alpaca/client.cpp
  •  Tags:  
  • c
  • Related