C++ Program to connect with MySQL - c++

I am new to C++ (although I have some experience with C) and MySQL and I am trying to make a program that reads a database from MySQL, I have been following this tutorial but I get an error when I try to 'build' the solution. (I am using Visual C++ 2008 just like they do in the tutorial.
Compiling...
test2.cpp
c:\users\rafael\documents\visual studio 2008\projects\test2\test2\test2.cpp(43) : warning C4244: 'initializing' : conversion from 'my_ulonglong' to 'unsigned int', possible loss of data
Compiling manifest to resources...
Microsoft (R) Windows (R) Resource Compiler Version 6.0.5724.0
Copyright (C) Microsoft Corporation. All rights reserved.
Linking...
test2.obj : error LNK2019: unresolved external symbol _mysql_close#4 referenced in function _main
test2.obj : error LNK2019: unresolved external symbol _mysql_fetch_row#4 referenced in function _main
test2.obj : error LNK2019: unresolved external symbol _mysql_num_rows#4 referenced in function _main
test2.obj : error LNK2019: unresolved external symbol _mysql_store_result#4 referenced in function _main
test2.obj : error LNK2019: unresolved external symbol _mysql_query#8 referenced in function _main
test2.obj : error LNK2019: unresolved external symbol _mysql_real_connect#32 referenced in function _main
test2.obj : error LNK2019: unresolved external symbol _mysql_init#4 referenced in function _main
C:\Users\*****\Documents\Visual Studio 2008\Projects\test2\Debug\test2.exe : fatal error LNK1120: 7 unresolved externals
I followed the tutorial and I cannot figure out what's going on, I guess it's something to do with the linkers, but I do not know what could I do.
This is the code I am using (source):
#include "stdafx.h"
#include "my_global.h" // Include this file first to avoid problems
#include "mysql.h" // MySQL Include File
#define SERVER "localhost"
#define USER "root"
#define PASSWORD "********"
#define DATABASE "test"
int main()
{
MYSQL *connect; // Create a pointer to the MySQL instance
connect=mysql_init(NULL); // Initialise the instance
/* This If is irrelevant and you don't need to show it. I kept it in for Fault Testing.*/
if(!connect) /* If instance didn't initialize say so and exit with fault.*/
{
fprintf(stderr,"MySQL Initialization Failed");
return 1;
}
/* Now we will actually connect to the specific database.*/
connect=mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0);
/* Following if statements are unneeded too, but it's worth it to show on your
first app, so that if your database is empty or the query didn't return anything it
will at least let you know that the connection to the mysql server was established. */
if(connect){
printf("Connection Succeeded\n");
}
else{
printf("Connection Failed!\n");
}
MYSQL_RES *res_set; /* Create a pointer to recieve the return value.*/
MYSQL_ROW row; /* Assign variable for rows. */
mysql_query(connect,"SELECT * FROM TABLE");
/* Send a query to the database. */
unsigned int i = 0; /* Create a counter for the rows */
res_set = mysql_store_result(connect); /* Receive the result and store it in res_set */
unsigned int numrows = mysql_num_rows(res_set); /* Create the count to print all rows */
/* This while is to print all rows and not just the first row found, */
while ((row = mysql_fetch_row(res_set)) != NULL){
printf("%s\n",row[i] != NULL ?
row[i] : "NULL"); /* Print the row data */
}
mysql_close(connect); /* Close and shutdown */
return 0;
}

Yes, it totally is a linker problem: it is almost surely missing the mysql library. In the project settings you should add the name (and the path) of the .lib you intend to use.

Related

Error while building MFC 4.1 project in MFC 6.0

I downloaded a project which was originally developed in MFC 4.1. I'm trying to build that project in MFC 6.0. When I opened it using Open WorkSpace, and build it, then following error came.
Link : fatal error LNK1104: cannot open file "mfc42ud.lib"
On internet I found a solution to fix this error by ignoring this library from Project settings. I did that and then another error on similar lines appeared for mfcs42ud.lib file. And I fixed that too.
When I added both the .lib files to ignore list, and build it, then I'm getting 901 errors like below....
--------------------Configuration: doodads - Win32 Unicode Debug-------------------- Linking... doodads.obj : error LNK2001:
unresolved external symbol __afxForceEXCLUDE ADDRESS.OBJ : error
LNK2001: unresolved external symbol __afxForceEXCLUDE expose.obj :
error LNK2001: unresolved external symbol __afxForceEXCLUDE
progress.obj : error LNK2001: unresolved external symbol
__afxForceEXCLUDE MaskDlg.obj : error LNK2001: unresolved external symbol __afxForceEXCLUDE SETKEY.OBJ : error LNK2001: unresolved
external symbol __afxForceEXCLUDE SPINNER.OBJ : error LNK2001:
unresolved external symbol __afxForceEXCLUDE stats.obj : error
LNK2001: unresolved external symbol __afxForceEXCLUDE ANIME.OBJ :
error LNK2001: unresolved external symbol __afxForceEXCLUDE STDAFX.OBJ
: error LNK2001: unresolved external symbol __afxForceEXCLUDE
MAINFRM.OBJ : error LNK2001: unresolved external symbol
__afxForceEXCLUDE DODADDOC.OBJ : error LNK2001: unresolved external symbol __afxForceEXCLUDE DoDadvw.obj : error LNK2001: unresolved
external symbol __afxForceEXCLUDE doodads.obj : error LNK2001:
unresolved external symbol __afxForceSTDAFX ADDRESS.OBJ : error
LNK2001: unresolved external symbol __afxForceSTDAFX expose.obj :
error LNK2001: unresolved external symbol __afxForceSTDAFX
progress.obj : error LNK2001: unresolved external symbol
__afxForceSTDAFX MaskDlg.obj : error LNK2001: unresolved external symbol __afxForceSTDAFX SETKEY.OBJ : error LNK2001: unresolved
external symbol __afxForceSTDAFX SPINNER.OBJ : error LNK2001:
unresolved external symbol __afxForceSTDAFX stats.obj : error LNK2001:
unresolved external symbol __afxForceSTDAFX ANIME.OBJ : error LNK2001:
unresolved external symbol __afxForceSTDAFX STDAFX.OBJ : error
LNK2001: unresolved external symbol __afxForceSTDAFX MAINFRM.OBJ :
error LNK2001: unresolved external symbol __afxForceSTDAFX
DODADDOC.OBJ : error LNK2001: unresolved external symbol
__afxForceSTDAFX DoDadvw.obj : error LNK2001: unresolved external symbol __afxForceSTDAFX
Here is the code file for your reference.
Add.h
// ADD.H - Header file for your Internet Server
// add Extension
#include "resource.h"
class CAddExtension : public CHttpServer
{
public:
CAddExtension();
~CAddExtension();
// Overrides
// ClassWizard generated virtual function overrides
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//{{AFX_VIRTUAL(CAddExtension)
public:
virtual BOOL GetExtensionVersion(HSE_VERSION_INFO* pVer);
//}}AFX_VIRTUAL
// TODO: Add handlers for your commands here.
// For example:
void Default(CHttpServerContext* pCtxt,
LPCTSTR pstrOp1, LPCTSTR pstrOp2);
DECLARE_PARSE_MAP()
//{{AFX_MSG(CAddExtension)
//}}AFX_MSG
};
Add.cpp
// ADD.CPP - Implementation file for your Internet Server
// add Extension
#include "stdafx.h"
#include "add.h"
#include <stdio.h>
///////////////////////////////////////////////////////////////////////
// command-parsing map
BEGIN_PARSE_MAP(CAddExtension, CHttpServer)
// TODO: insert your ON_PARSE_COMMAND() and
// ON_PARSE_COMMAND_PARAMS() here to hook up your commands.
// For example:
ON_PARSE_COMMAND(Default, CAddExtension, ITS_PSTR ITS_PSTR)
ON_PARSE_COMMAND_PARAMS("opone=~ optwo=~")
DEFAULT_PARSE_COMMAND(Default, CAddExtension)
END_PARSE_MAP(CAddExtension)
///////////////////////////////////////////////////////////////////////
// The one and only CAddExtension object
CAddExtension theExtension;
///////////////////////////////////////////////////////////////////////
// CAddExtension implementation
CAddExtension::CAddExtension()
{
}
CAddExtension::~CAddExtension()
{
}
BOOL CAddExtension::GetExtensionVersion(HSE_VERSION_INFO* pVer)
{
// Call default implementation for initialization
CHttpServer::GetExtensionVersion(pVer);
// Load description string
TCHAR sz[HSE_MAX_EXT_DLL_NAME_LEN+1];
ISAPIVERIFY(::LoadString(AfxGetResourceHandle(),
IDS_SERVER, sz, HSE_MAX_EXT_DLL_NAME_LEN));
_tcscpy(pVer->lpszExtensionDesc, sz);
return TRUE;
}
///////////////////////////////////////////////////////////////////////
// CAddExtension command handlers
void CAddExtension::Default(CHttpServerContext* pCtxt,
LPCTSTR pstrOp1, LPCTSTR pstrOp2)
{
StartContent(pCtxt);
WriteTitle(pCtxt);
int nOp1;
int nOp2;
if (*pstrOp1 != '~' && *pstrOp2 != '~')
{
nOp1 = atoi(pstrOp1);
nOp2 = atoi(pstrOp2);
char sz[1024];
sprintf(sz, "The result is: %d\n", nOp1 + nOp2);
*pCtxt << sz;
}
else
{
*pCtxt << "<FORM ACTION=\"http://mooseboy/add.dll\" METHOD=\"GET\">";
*pCtxt << "Enter the first number: <INPUT TYPE=\"text\" NAME=\"opone\" VALUE=\"0\" SIZE=10><p>";
*pCtxt << "Enter the second number: <INPUT TYPE=\"text\" NAME=\"optwo\" VALUE=\"0\" SIZE=10><p>";
*pCtxt << "<p> <INPUT TYPE = \"SUBMIT\" VALUE=\"Add it up\">";
*pCtxt << "</FORM>";
}
EndContent(pCtxt);
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CAddExtension, CHttpServer)
//{{AFX_MSG_MAP(CAddExtension)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
///////////////////////////////////////////////////////////////////////
// If your extension will not use MFC, you'll need this code to make
// sure the extension objects can find the resource handle for the
// module. If you convert your extension to not be dependent on MFC,
// remove the comments arounn the following AfxGetResourceHandle()
// and DllMain() functions, as well as the g_hInstance global.
static HINSTANCE g_hInstance;
HINSTANCE AFXISAPI AfxGetResourceHandle()
{
return g_hInstance;
}
BOOL WINAPI DllMain(HINSTANCE hInst, ULONG ulReason,
LPVOID lpReserved)
{
if (ulReason == DLL_PROCESS_ATTACH)
{
g_hInstance = hInst;
}
return TRUE;
}
Just for information, I've marked Microsoft Foundation Classes to Use MFC in a shared DLL under General tab. Please help, TIA.
MFC 6.0 uses MFC42*.LIB library files (strange but true). So it seems you link with the correct filenames.
If you get these error messages when you link your project, I guess that either your project file has something wrong, or Visual C++ 6 is not correctly installed. The solution is not to remove these libraries, but to find out why Visual C++ doesn't find them.
Your project is compiling in unicode-debug configuration. Have you installed the unicode libraries when you have installed Visual C++? Maybe this is an opt-in install option (not sure). Can you build your project using another configuration, like release-unicode? Or Debug?
What can help you is to create a new empty Visual C++/MFC project (File/New Project/C++/MFC/MFC Application), so will get a valid MFC project configuration. Be sure to choose Unicode configuration, because this is the configuration you want to use.

Adding htmlhelp to project

I'm trying, without much luck, to add chm options to an existing project.
Main.cpp has this:
#include "HtmlHelp.h"
int OpenHelp(LPTSTR arg1)
{
HWND _Hhdl = HtmlHelp(GetDesktopWindow(), arg1, HH_DISPLAY_TOPIC, NULL);
return 1;
}
htmlhelp.lib is set in Linker/Input/additional Dependencies.
The error I'm getting is:
main.obj : error LNK2019: unresolved external symbol _HtmlHelpW#16 referenced in function "int __cdecl OpenHelp(wchar_t *)" (?OpenHelp##YAHPA_W#Z)
I'm new to C++ so I'm assuming my function is at fault somehow.
The idea was the function would be passed a sting in the "C:\Help.chm\::/Topic.html" format.

error LNK2019: unresolved external symbol "public: [duplicate]

This question already has answers here:
Why do I get "unresolved external symbol" errors when using templates? [duplicate]
(3 answers)
error LNK2019 unresolved external symbol
(1 answer)
Closed 9 years ago.
Relearning C++ for the sake of using OpenCL. I have created a Helper Class called CheckDevice which has a bunch of boiler plate code for getting device stats.
CheckDevice.h
class Utils
{
public:
Utils(){};
~Utils(){};
template<class T>
static bool IsNull(T Object, char* name);
private:
};
CheckDevice.cpp
cl_command_queue Utils::CreateCommandQueue(cl_context context, cl_device_id *device)
{
cl_int err;
cl_device_id *devices;
cl_command_queue queue = NULL;
size_t deviceBufferSize = -1;
cl_kernel kernel = 0;
Utils::IsNull<cl_command_queue>(queue, "Utils::CreateCommandQueue::queue");
return queue;
}
main.cpp
void main()
{
cl_kernel kernel = 0;
Utils::IsNull<cl_kernel>(kernel, "clCreateKernel");
}
The question is when calling the function Utils::IsNull from within CheckDevice.cpp it works fine but when calling from main.cpp than I get the following in Visual Studios 2012
error LNK2019: unresolved external symbol "public: static bool __cdecl Utils::IsNull(struct _cl_kernel *,char *)" (??$IsNull#PAU_cl_kernel###Utils##SA_NPAU_cl_kernel##PAD#Z) referenced in function _main
1>C:\Users\Suri\Documents\Visual Studio 2012\Projects\HelloWorld\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
Any Help would be apperciated
You don't show the implementation of the IsNull template, but probably it is in CheckDevice.cpp. It should be placed in CheckDevice.h instead, the compiler needs to see it's definition to be able to instantiate it.
There is a calling convention problem on the main.cpp. When you are trying to make a function call on the main, you need first to create an instance of that class object, before you make a function call. You are missing that on your main.
So basically you need to create an instance of Utils and make a reference to it.
cl_kernel kernel = 0;
Utils *ut = new Utils();
ut->IsNull"<"cl_kernel">"(kernel, "clCreateKernel");

Calling MATLAB from C++ errors: unresolved external symbol

I encounter several errors when calling my MATLAB function from C++. The main idea is: firstly compile a MATLAB function and generate DLL file, and then include .h and .lib files in C++. Finally, write .cpp to test and call the function. Here's my detailed steps and please tell me where I'm wrong.
(Using MATLAB 2012b and Visual C++ 2008, Windows 7 64-bit)
In MATLAB:
mbuild -setup and mex -setup to set Visual Microsoft Visual C++ 2008 SP1 as the compiler.
Create MyAdd.m in folder C:\Users\WangYudong\Documents\MATLAB\MyAdd_M and the function is like:
function [c] = MyAdd(a, b)
c = a + b;
mcc -W cpplib:libMyAdd -T link:lib MyAdd to compile MyAdd.m and generate several files including libMyAdd.dll, libMyAdd.h, libMyAdd.lib and other files.
In C++
Select VC++ Directories → Include files to add E:\MATLAB\R2012b\extern\include.
Select VC++ Directories → Library files to add
E:\MATLAB\R2012b\extern\lib\win64\microsoft and
C:\Users\WangYudong\Documents\MATLAB\MyAdd_M.
Select Linker → Input → Additional Dependencies to add new entries:
mclmcr.lib
mclmcrrt.lib
libmx.lib
libmat.lib
libMyAdd.lib
Create a new MyAdd_test.cpp and put libMyAdd.dll, libMyAdd.h and libMyAdd.lib in the same folder. Add libMyAdd.h in Header Files, libMyAdd.h and libMyAdd.lib in Resource Files.
Code of MyAdd_test.cpp is like:
#include "mclmcr.h"
#include "matrix.h"
#include "mclcppclass.h"
#include "libMyAdd.h"
int main() {
double a = 6;
double b = 9;
double c;
// initialize lib
if( !libMyAddInitialize()) {
std::cout << "Could not initialize libMyAdd!" << std::endl;
return -1;
}
// allocate space
mwArray mwA(1, 1, mxDOUBLE_CLASS);
mwArray mwB(1, 1, mxDOUBLE_CLASS);
mwArray mwC(1, 1, mxDOUBLE_CLASS);
// set data
mwA.SetData(&a, 1);
mwB.SetData(&b, 1);
// use function: MyAdd
MyAdd(1, mwC, mwA, mwB);
// get data
c = mwC.Get(1, 1);
printf("c is %f\n", c);
// terminate the lib
libMyAddTerminate();
// terminate MCR
mclTerminateApplication();
return 0;
}
At last, the result is
Compiling...
MyAdd_test.cpp
Linking...
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclTerminateApplication_proxy referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol _libMyAddTerminate referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) void __cdecl MyAdd(int,class mwArray &,class mwArray const &,class mwArray const &)" (__imp_?MyAdd##YAXHAAVmwArray##ABV1#1#Z) referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol _libMyAddInitialize referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclGetMatrix referenced in function "public: __thiscall mwArray::mwArray(unsigned int,unsigned int,enum mxClassID,enum mxComplexity)" (??0mwArray##QAE#IIW4mxClassID##W4mxComplexity###Z)
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclcppGetLastError referenced in function "public: static void __cdecl mwException::raise_error(void)" (?raise_error#mwException##SAXXZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclcppCreateError referenced in function "public: __thiscall mwException::mwException(void)" (??0mwException##QAE#XZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _ref_count_obj_addref referenced in function "public: __thiscall mwException::mwException(class mwException const &)" (??0mwException##QAE#ABV0##Z)
MyAdd_test.obj : error LNK2019: unresolved external symbol _ref_count_obj_release referenced in function "public: virtual __thiscall mwException::~mwException(void)" (??1mwException##UAE#XZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _error_info_get_message referenced in function "public: virtual char const * __thiscall mwException::what(void)const " (?what#mwException##UBEPBDXZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _array_ref_getV_int referenced in function "public: class mwArray __cdecl mwArray::GetPromoted(unsigned int,...)" (?GetPromoted#mwArray##QAA?AV1#IZZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _array_ref_set_numeric_mxDouble referenced in function "public: void __thiscall mwArray::SetData(double *,unsigned int)" (?SetData#mwArray##QAEXPANI#Z)
MyAdd_test.obj : error LNK2019: unresolved external symbol _array_ref_get_numeric_mxDouble referenced in function "public: __thiscall mwArray::operator double(void)const " (??BmwArray##QBENXZ)
C:\Users\WangYudong\Documents\Visual Studio 2008\Projects\MyAdd_C\Debug\MyAdd_C.exe : fatal error LNK1120: 13 unresolved externals
Actually, the work above is my test to call a custom MATLAB function from C++. My following work is to convert a MATLAB program to C++, which contains image processing functions like imread, edge, strel, etc. I've tried MATLAB Coder, but it can't convert MATLAB functions. So I try the method above. Is it an efficient way to convert those functions or should I implement them using OpenCV?
Before you start, make sure you have a supported compiler installed. That would be Visual C++ and possibly Windows SDK if you are using VS Express edition on a 64-bit Windows. Next you need to configure MATLAB by running these steps at least once:
>> mex -setup
>> mbuild -setup
Now given the following simple function:
MyAdd.m
function c = MyAdd(a,b)
c = a + b;
end
We want to build a C++ shared library using the MATLAB Compiler mcc:
>> mcc -N -W cpplib:libMyAdd -T link:lib MyAdd.m -v
This will produce a couple of files including a header file, a DLL, and an import library:
libMyAdd.h
libMyAdd.dll
libMyAdd.lib
Next we create a C++ program to test the above library:
MyAdd_test.cpp
#include "libMyAdd.h"
int main()
{
// initialize MCR and lib
if (!mclInitializeApplication(NULL,0)) {
std::cerr << "could not initialize the application" << std::endl;
return -1;
}
if(!libMyAddInitialize()) {
std::cerr << "Could not initialize the library" << std::endl;
return -1;
}
try {
// create input
double a[] = {1.0, 2.0, 3.0, 4.0};
double b[] = {5.0, 6.0, 7.0, 8.0};
mwArray in1(2, 2, mxDOUBLE_CLASS, mxREAL);
mwArray in2(2, 2, mxDOUBLE_CLASS, mxREAL);
in1.SetData(a, 4);
in2.SetData(b, 4);
// call function
mwArray out;
MyAdd(1, out, in1, in2);
// show result
std::cout << "in1 + in2 = " << std::endl;
std::cout << out << std::endl;
double c[4];
out.GetData(c, 4);
for(int i=0; i<4; i++) {
std::cout << c[i] << " " << std::endl;
}
} catch (const mwException& e) {
std::cerr << e.what() << std::endl;
return -2;
} catch (...) {
std::cerr << "Unexpected error thrown" << std::endl;
return -3;
}
// cleanup
libMyAddTerminate();
mclTerminateApplication();
return 0;
}
We could compile this program right from inside MATLAB using:
>> mbuild MyAdd_test.cpp libMyAdd.lib -v
>> !MyAdd_test
We could also compile it ourselves using Visual Studio. We start by creating a native console application, then set the project settings as follows:
From the menu, select "Project > Properties" and apply the settings to "All configurations" (both debug and release targets)
Under C/C++ properties, set the "Additional Include Directories" by adding both the directory containing the generated header file libMyAdd.h, in addition to the directory containing MATLAB's header files:
$matlabroot\extern\include
Similarly under "Linker", set the "Additional Library Directories". That would be the same directory as before containing libMyAdd.lib, as well as in my case:
$matlabroot\extern\lib\win32\microsoft
Then go to "Linker > Input" and add the following inside "Additional Dependencies":
libMyAdd.lib
mclmcrrt.lib
Finally under "Debugging > Environment", you might want to extend the PATH environment variable to include the directory containing the generated libMyAdd.dll file. That way you can directly hit F5 to compile run the program directly from inside VS. This will be something like:
PATH=%PATH%;C:\path\to\output\folder
If you do this kind of thing often, you could create a property sheet once, which could then be reused in other VC++ projects. See this answer for an example.

lnk2019 visual studio error

I am trying to make a simple UDP socket class to do some talking between a c++ program and a java program so I'm trying to make a socket class that handles all the UDP transmission but I can't get the program to compile because I get about 8 lnk2019 errors and I have no idea what they even mean. I mainly work in Java and only use c++ when I have to lol. I have 3 files the socket header and code. Also the Udp Socket code is from rFactor-Nesim so the socket code isn't written by me.
UdpSocket.cpp
#include "UdpSocket.hpp"
#include <stdio.h>
UdpSocket::UdpSocket(const char* host, int port)
: mHost(host), mPort(port)
{
}
UdpSocket::~UdpSocket(void)
{
}
void UdpSocket::Open()
{
if(WSAStartup(MAKEWORD(2, 0), &mWinsockData) != 0)
fprintf(stderr, "WSAStartup() failed");
if ((mSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
perror("socket() failed");
memset(&mSocketAddress, 0, sizeof(mSocketAddress));
mSocketAddress.sin_family = AF_INET;
mSocketAddress.sin_addr.s_addr = inet_addr(mHost);
mSocketAddress.sin_port = htons(mPort);
}
void UdpSocket::Close()
{
closesocket(mSocket);
WSACleanup();
}
void UdpSocket::Send(char* str, size_t length)
{
size_t result = sendto(mSocket, str, length, 0,
(struct sockaddr *) &mSocketAddress, sizeof(mSocketAddress));
if(result != length)
perror("sendto() sent incorrect number of bytes");
}
UdpSocket.hpp
#ifndef UDPSOCKET_HPP
#define UDPSOCKET_HPP
#include <WinSock.h>
class UdpSocket
{
public:
UdpSocket(const char* host, int port);
~UdpSocket(void);
void Send(char* str, size_t length);
void Open();
void Close();
private:
const char* mHost;
int mPort;
int mSocket;
struct sockaddr_in mSocketAddress;
WSADATA mWinsockData;
};
#endif // UDPSOCKET_HPP
and the main
#include "Socket/UdpSocket.hpp"
#include <iostream>
int Main(){
UdpSocket* testSocket = new UdpSocket("127.0.0.1", 27469);
testSocket->Open();
system("pause");
return 0;
}
Any help would be great. I'm not very strong with c++ but I have done a little bit
Console Ouput:
Error 1 error LNK2019: unresolved external symbol __imp__htons#4 referenced in function "public: void __thiscall UdpSocket::Open(void)" (?Open#UdpSocket##QAEXXZ) UdpSocket.obj SocketTest
Error 2 error LNK2019: unresolved external symbol __imp__inet_addr#4 referenced in function "public: void __thiscall UdpSocket::Open(void)" (?Open#UdpSocket##QAEXXZ) UdpSocket.obj SocketTest
Error 3 error LNK2019: unresolved external symbol __imp__socket#12 referenced in function "public: void __thiscall UdpSocket::Open(void)" (?Open#UdpSocket##QAEXXZ) UdpSocket.obj SocketTest
Error 4 error LNK2019: unresolved external symbol __imp__WSAStartup#8 referenced in function "public: void __thiscall UdpSocket::Open(void)" (?Open#UdpSocket##QAEXXZ) UdpSocket.obj SocketTest
Error 5 error LNK2019: unresolved external symbol __imp__WSACleanup#0 referenced in function "public: void __thiscall UdpSocket::Close(void)" (?Close#UdpSocket##QAEXXZ) UdpSocket.obj SocketTest
Error 6 error LNK2019: unresolved external symbol __imp__closesocket#4 referenced in function "public: void __thiscall UdpSocket::Close(void)" (?Close#UdpSocket##QAEXXZ) UdpSocket.obj SocketTest
Error 7 error LNK2019: unresolved external symbol __imp__sendto#24 referenced in function "public: void __thiscall UdpSocket::Send(char *,unsigned int)" (?Send#UdpSocket##QAEXPADI#Z) UdpSocket.obj SocketTest
Error 8 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup MSVCRTD.lib SocketTest
Error 9 fatal error LNK1120: 8 unresolved externals C:\Users\Brendan\Documents\Visual Studio 2008\Projects\SocketTest\Debug\SocketTest.exe SocketTest
It sounds like you're failing to link against Winsock - Ws2_32.lib
If you're building from the command line, add Ws2_32.lib to your link command line.
If you're building from Visual Studio, look for linker flags/settings inside a project configuration dialog.
when you have code in several implementation files, you need to compile all those implementation files and pass the resulting object code files to the linker, which combines them (and other stuff) into an executable
it's not enough to include the header of a module
c++ doesn't (yet) have any technical module concept, so including headers does not magically compile implementation files or pass object code files to the linker
this is not part of the c++ standard, but it's part of everyday tool usage
the linker is telling you that you failed to provide it with object code for your class member functions the Winsock library
that object code is provided by the library file, in visual c++ typically with filename extension ".lib"
in general, when you get a mysterious error, just look up the error number in the documentation
in visual studio that's as simple as pressing the F1 key