I’m trying to include some networking code into my C++ application. I downloaded CSimpleSocket and I copied all the .h and .cpp files into the directory where my main file is. Then I tried including one of the headers, but the linker just barfs up a bunch of errors, like:
- [Linker error] undefined reference to CPassiveSocket::CPassiveSocket(CSimpleSocket::CSocketType)’
- [Linker error] undefined reference to `CSimpleSocket::Initialize()’
- [Linker error] undefined reference to `CPassiveSocket::Listen(unsigned char const*, short, int)’
- [Linker error] undefined reference to `CPassiveSocket::Accept()’
and others. Everything is in one directory, so I don’t think that’s the problem. The code I’m using to include is #include "PassiveSocket.h". I’m using Dev-C++, if that makes any difference. I don’t understand what I’m doing wrong, so if somebody could help me, that would be great.
Forgive me if this is a really dumb question, but I’m trying to learn C++, and it’s not easy. Thanks for your help.
The reason you’re getting this error is because your compiler can’t find the binary that corresponds to the CSimpleSocket headers. It’s as if you wrote
And then never provided the implementation for someFunction.
To use a third party library you need two things:
Once you’ve got your header files and library files you need to put them in a place your compiler can find them. This place will vary depending on your OS, environment variables and compiler configuration.
Now that they’re somewhere the compiler can find them you need to tell the compiler to use them. Header files are used with the #include command and library files are linked by providing arguments to the compiler.
Behind the scenes Dev-C++ uses the MinGW GNU GCC compiler, it invokes a command similar to
g++ file1.cpp file2.cpp ... filen.cpp -o filenamethat tells the program g++ to compile a C++ executable named “filename” using files 1 to n. There are other flags that can be added to g++ such as telling it where to search and what to link.The name of the CSimpleSocket library when compiled is “clsocket” so we need to find a way to configure Dev-C++ to add
-lclsocketto theg++command. I don’t use Dev-C++ so I can’t help you here but you’re probably looking for “Linking Options” or something similar in your compile configuration. You also need to make sure the .lib and .h files are on the search path which should also be configurable in Dev-C++.CSimpleSocket also provides an installer that should automatically create the .lib file and place the .lib and .h in places where they can be found, you should consider using that installer.
I think the complexity of this answer highlights the abysmal state of the C++ library integration ecosystem. Unfortunately there is no concept of a “module” in C++ at the time of writing.