Shaun Parsons
Shaun Parsons

Reputation: 362

C 11 error: ‘X’ was not declared in this scope

I'm getting the following errors in my code, and I'm unsure why since 'socketfd' is declared in client.hpp and is used in the constructor within client.cpp but then when I try and use it later I am getting an error.

Terminal output:

g++ client.cpp -o client.o -pthread -c -std=c++11
client.cpp: In function ‘void sendMessage(std::string)’:
client.cpp:37:23: error: ‘socketfd’ was not declared in this scope

client.hpp

#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netdb.h>

class Client {

    public:
        Client();
        ~Client();
        void sendMessage(std::string);

    private:
        int status, socketfd;
        struct addrinfo host_info;
        struct addrinfo *host_info_list;

};

client.cpp

#include "client.hpp"


Client::Client() {
    memset(&host_info, 0, sizeof host_info);
    std::cout << "Setting up the structs..." << std::endl;
    host_info.ai_family = AF_UNSPEC;
    host_info.ai_socktype = SOCK_STREAM;
    status = getaddrinfo("192.168.1.3", "8888", &host_info, &host_info_list);
    if (status != 0) {
        std::cout << "getaddrinfo error " << gai_strerror(status);
    }

    std:: cout << "Creating a socket..." << std::endl;
    socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol);
    if (socketfd == -1) {
        std::cout << "Socket Errror ";
    }
    std::cout << "Connecting..." << std::endl;
    status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
    if (status == -1) {
        std::cout << "Connect Error" << std::endl;
    }
    std::cout << "Successfully Connected" << std::endl;
}

Client::~Client() {

}

void sendMessage(std::string msg) {
    std::cout << "Sending Message: " << msg << std::endl;
    int len;
    ssize_t bytes_sent;
    len = strlen(msg.c_str());
    bytes_sent = send(socketfd, msg.c_str(), len, 0);
}

This is some of the first C++ I've done, and I'm a bit confused why I am getting this error.

Upvotes: 1

Views: 1535

Answers (2)

suspectus
suspectus

Reputation: 17288

The function signature of sendMessage is not that of a member function. Try this-:

  void Client::sendMessage(std::string msg) {

Upvotes: 4

NPE
NPE

Reputation: 500673

You're missing Client:: before sendMessage():

void Client::sendMessage(std::string msg) {
     ^^^^^^^^

Upvotes: 5

Related Questions