-1

I want to make my own header file that has functions that I can call when trying to make a tcp connection, I have three files main.cpp,sock.hpp,sock.cpp

main.cpp contains

#include <stdio.h>
#include <stdlib.h>
#include "sock.hpp"

int main()
{
        create_sock("0.0.0.0","1337");
        return 0;
}

sock.hpp has

#ifndef SOCKS_H
#define SOCKS_H
#endif  

int create_sock(const char * host , const char * port);

sock.cpp has

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string.h>


int create_sock( const char * host , const char * port)
{
        INT WSAAPI iResult;
        return 0;
}

when compiling using the command g++ main.cpp sock.cpp -lws2_32 this results in the following error

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\cc1epM1h.o:main.cpp:(.text+0x31): undefined reference to `create_sock(char*, char*)'
collect2.exe: error: ld returned 1 exit status
  • 2
    `create_sock(const char * host ...` is different from `create_sock(char * host ...` – Richard Critten May 13 '22 at 10:54
  • 1
    You have placed `#endif` at the wrong place(look closely in sock.hpp). to solve this move the `#endif` inside `sock.hpp` after the declaration of `create_sock`. Also, in the *declaration* of `create_sock` the parameters are `char*` while in the *definition* they are `const char*`. – Anoop Rana May 13 '22 at 10:54
  • @AnoopRana this is just the bare minimum example of the problem – stack_getto May 13 '22 at 10:57
  • @AnoopRana i still get this error – stack_getto May 13 '22 at 10:58
  • @stack_getto what do you mean? **There are 2 problems with your code**. First is that the `#endif` should be placed after the declaration of `create_sock`. Second is that the parameters in the declaration and definition doesnt match. See [working demo](https://onlinegdb.com/NuJmkb5pz). – Anoop Rana May 13 '22 at 10:59
  • @AnoopRana i moved `#endif` to the end of the `.hpp` file but i still get the same error – stack_getto May 13 '22 at 11:00
  • @stack_getto See [working demo](https://onlinegdb.com/NuJmkb5pz). – Anoop Rana May 13 '22 at 11:01
  • @AnoopRana i did like so but i still get the error – stack_getto May 13 '22 at 11:03
  • 1
    @stack_getto I provided a [working demo](https://onlinegdb.com/NuJmkb5pz). Please match that code with your own code to debug(find out) what you're doing wrong. I have already explained the problems and given a solution. – Anoop Rana May 13 '22 at 11:04

0 Answers0