I'm trying to convert a bmp image to a png one with this code:
#define WIN32_LEAN_AND_MEAN
#define _CRT_SECURE_NO_DEPRECATE
#include <png.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
void GetDesktopResolution(int& horizontal, int& vertical)
{
RECT desktop;
// Get a handle to the desktop window
const HWND hDesktop = GetDesktopWindow();
// Get the size of screen to the variable desktop
GetWindowRect(hDesktop, &desktop);
// The top left corner will have coordinates (0,0)
// and the bottom right corner will have coordinates
// (horizontal, vertical)
horizontal = desktop.right;
vertical = desktop.bottom;
}
typedef struct _RGBPixel {
uint8_t blue;
uint8_t green;
uint8_t red;
} RGBPixel;
/* Structure for containing decompressed bitmaps. */
typedef struct _RGBBitmap {
RGBPixel *pixels;
size_t width;
size_t height;
size_t bytewidth;
uint8_t bytes_per_pixel;
} RGBBitmap;
/* Returns pixel of bitmap at given point. */
#define RGBPixelAtPoint(image, x, y) \
*(((image)->pixels) + (((image)->bytewidth * (y)) \
+ ((x) * (image)->bytes_per_pixel)))
/* Attempts to save PNG to file; returns 0 on success, non-zero on error. */
int save_png_to_file(RGBBitmap *bitmap, const char *path)
{
FILE *fp = fopen(path, "wb");
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
size_t x, y;
png_uint_32 bytes_per_row;
png_byte **row_pointers = NULL;
if (fp == NULL) return -1;
/* Initialize the write struct. */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
fclose(fp);
return -1;
}
/* Initialize the info struct. */
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_write_struct(&png_ptr, NULL);
fclose(fp);
return -1;
}
/* Set up error handling. */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return -1;
}
/* Set image attributes. */
png_set_IHDR(png_ptr,
info_ptr,
bitmap->width,
bitmap->height,
8,
PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
/* Initialize rows of PNG. */
bytes_per_row = bitmap->width * bitmap->bytes_per_pixel;
png_malloc(png_ptr, bitmap->height * sizeof(png_byte *));
for (y = 0; y < bitmap->height; ++y) {
uint8_t *row = (uint8_t *)png_malloc(png_ptr, sizeof(uint8_t)* bitmap->bytes_per_pixel);
row_pointers[y] = (png_byte *)row;
for (x = 0; x < bitmap->width; ++x) {
RGBPixel color = RGBPixelAtPoint(bitmap, x, y);
*row++ = color.red;
*row++ = color.green;
*row++ = color.blue;
}
}
/* Actually write the image data. */
png_init_io(png_ptr, fp);
png_set_rows(png_ptr, info_ptr, row_pointers);
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
/* Cleanup. */
for (y = 0; y < bitmap->height; y++) {
png_free(png_ptr, row_pointers[y]);
}
png_free(png_ptr, row_pointers);
/* Finish writing. */
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return 0;
}
int main()
{
RGBBitmap rgbbitmap;
int w, h;
GetDesktopResolution(w, h);
rgbbitmap.height = h;
rgbbitmap.width = w;
rgbbitmap.bytes_per_pixel = 1;
rgbbitmap.bytewidth = w / 100;
RGBPixel rgbpixel;
rgbpixel.blue = 100;
rgbpixel.green = 100;
rgbpixel.red = 100;
rgbbitmap.pixels = &rgbpixel;
save_png_to_file(&rgbbitmap, "abc.bmp");
return 0;
}
Executing this code triggers these errors :
LNK1120: 9 unresolved externals
LNK2019: unresolved external symbol _png_create_info_struct referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_create_write_struct referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_destroy_write_struct referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_free referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_init_io referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_malloc referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_set_IHDR referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_set_rows referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
LNK2019: unresolved external symbol _png_write_png referenced in function "int __cdecl save_png_to_file(struct _RGBBitmap *,char const *)" (?save_png_to_file##YAHPAU_RGBBitmap##PBD#Z)
I'm not able to find how to fix these errors. Any brilliant suggestion, please?
I'm currently using Visual Studio Ultimate 2013 on a Windows 7 SP1 plateform.
Thanks a lot!
I think, you didn't linked your libraries, just included headers. This question anwers how you do it...
If not, there is plently of what can happen:
you are trying to call those functions with bad parameters
you included bad header file
you have mixed libraries or you are trying to link MinGW, VS2012/VS2012 compiled library to VS2013 compiler, since i don't know if they are compatible...
You can try to download png library, create VS2012 project and try to compile it. When you do, you should absolutely have no problems while linking...
Related
My project is a c++ CLR/CLI, I have some PNG images in my Resource Files and I want to change the BackgroundImage of a System::Windows::Forms::Button when the button is clicked, my code below:
#include <Windows.h>
#include "resource.h"
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
HBITMAP hBitMap = (HBITMAP) LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_PNG2), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
Bitmap^ bitMap = Bitmap::FromHbitmap((IntPtr) hBitMap);
DeleteObject(hBitMap);
button1->BackgroundImage = (System::Drawing::Image^) bitMap;
}
Here's my resource.h:
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Disneyy.rc
//
#define IDB_PNG1 101
#define IDB_PNG2 102
#define IDB_PNG3 103
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 104
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
When compiling I'm getting this error:
1>MyForm.obj : error LNK2028: unresolved token (0A000036) "extern "C" void * __stdcall LoadImageW(struct HINSTANCE__ *,wchar_t const *,unsigned int,int,int,unsigned int)" (?LoadImageW##$$J224YGPAXPAUHINSTANCE__##PB_WIHHI#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
1>MyForm.obj : error LNK2028: unresolved token (0A00003F) "extern "C" int __stdcall DeleteObject(void *)" (?DeleteObject##$$J14YGHPAX#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
1>MyForm.obj : error LNK2019: unresolved external symbol "extern "C" void * __stdcall LoadImageW(struct HINSTANCE__ *,wchar_t const *,unsigned int,int,int,unsigned int)" (?LoadImageW##$$J224YGPAXPAUHINSTANCE__##PB_WIHHI#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
1>MyForm.obj : error LNK2019: unresolved external symbol "extern "C" int __stdcall DeleteObject(void *)" (?DeleteObject##$$J14YGHPAX#Z) referenced in function "private: void __clrcall Disneyy::MyForm::button1_Click(class System::Object ^,class System::EventArgs ^)" (?button1_Click#MyForm#Disneyy##$$FA$AAMXP$AAVObject#System##P$AAVEventArgs#4##Z)
EDIT:
Ok I fixed it by adding User32.lib to Additional Dependencies also specifying the Entry Point as main. However there's something wrong with this line:
HBITMAP hBitMap = (HBITMAP) LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_PNG2), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
Now I'm getting this error:
First-chance exception at 0x77130c3f in Disneyy.exe: 0xC0000005: Access violation reading location 0x00000066.
A first chance exception of type 'System.AccessViolationException' occurred in Disneyy.exe
An unhandled exception of type 'System.AccessViolationException' occurred in Disneyy.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
EDIT:
Once again I fixed it by changing IMAGE_BITMAP to BI_PNG, but now a new error comes up at line: Bitmap^ bitMap = Bitmap::FromHbitmap((IntPtr) hBitMap);
A first chance exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
Additional information: A generic error occurred in GDI+.
Finally after hours and hours of research I found an adapted solution which works just fine!
This solution is a combination of Giuseppe Pischedda's answer: https://www.codeproject.com/Articles/17996/Load-JPEG-images-from-DLL-with-LoadResource-in-Man
and Bordon's answer: https://social.msdn.microsoft.com/Forums/de-DE/c8dea6f9-0564-49d6-9782-117207031140/loadfromresource-fails-for-loading-png-files-from-resource?forum=vcmfcatl
adapted by me for PNG images:
public: System::Drawing::Image^ getImageFromRes(long resource_ID) {
// Function getImageFromRes
// A function for loading PNG images from resources in C++ CLR/CLI
// Copyright (C) Giuseppe Pischedda 2007 for most code
// and a little part of this code by Bordon and adapted by me for PNG images in C++ CLR/CLI.
//Load the resource module:
HMODULE hInst = NULL;
// Find the resource using the resource ID from file "resource.h"
HRSRC hResource = ::FindResource(hInst, MAKEINTRESOURCE(resource_ID), L"PNG");
if (!hResource) return nullptr;
// Load the resource and save the total size.
DWORD Size = SizeofResource(hInst, hResource);
HGLOBAL MemoryHandle = LoadResource(hInst, hResource);
if (MemoryHandle == NULL) return nullptr;
//Create a cli::array of byte with size = total size + 2
cli::array<BYTE>^ MemPtr = gcnew array<BYTE>(Size + 2);
//Cast from LPVOID to char *
char *lkr = (char *) (LockResource(MemoryHandle));
//Copy from unmanaged memory to managed array
System::Runtime::InteropServices::Marshal::Copy((IntPtr) lkr, MemPtr, 0, Size);
// Create a new MemoryStream with size = MemPtr
System::IO::MemoryStream^ stream = gcnew System::IO::MemoryStream(MemPtr);
//Write in the MemoryStream
stream->Write(MemPtr, 0, Size);
//Set the position for read the stream
stream->Position = 0;
//Free allocated resources
FreeLibrary(hInst);
//Create an Image abstract class pointer
System::Drawing::Image^ ptrPNG;
//Assign the stream to abstract class pointer
ptrPNG = System::Drawing::Image::FromStream(stream);
return ptrPNG;
}
Usage:
System::Drawing::Image^ image = getImageFromRes(IDB_PNG2);
if (image != nullptr) button1->BackgroundImage = image;
Iam modding in the source Engine and iam trying to add adobe Flash into it
i have already included header files and the libs from Microsoft DirectX SDK (June 2010) in visual studio 2010 but when Compiling the project it give me errors
1>FlashManager.obj : error LNK2019: unresolved external symbol _D3DXCreateSprite#8 referenced in function "public: bool __thiscall FlashManager::RecreateTargets(struct IDirect3DDevice9 *)" (?RecreateTargets#FlashManager##QAE_NPAUIDirect3DDevice9###Z)
1>FlashManager.obj : error LNK2019: unresolved external symbol _D3DXMatrixTransformation2D#28 referenced in function "public: void __thiscall FlashManager::SceneDataHook(void)" (?SceneDataHook#FlashManager##QAEXXZ)
1>FlashManager.obj : error LNK2019: unresolved external symbol "struct IFlashDX * __cdecl GetFlashToDirectXInstance(void)" (?GetFlashToDirectXInstance##YAPAUIFlashDX##XZ) referenced in function "public: __thiscall FlashManager::FlashManager(void)" (??0FlashManager##QAE#XZ)
1>.\Release_sdk\Client.dll : fatal error LNK1120: 3 unresolved externals
How Can i fix it
linked every thing
The code
bool FlashManager::RecreateTargets(IDirect3DDevice9* pD3DDevice)
{
HRESULT hr;
int movieIndex = GetPlayingMovieIndex();
int newWidth = -1, newHeight = -1;
if (movieIndex > -1)
{
newWidth = m_movieArray[movieIndex].GetWidth();
newHeight = m_movieArray[movieIndex].GetHeight();
}
else
{
newWidth = w;
newHeight = h;
}
hr = pD3DDevice->CreateTexture(newWidth, newHeight, 1, 0, transparency_mode ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &g_Texture, NULL);
if (FAILED(hr))
return false;
D3DXCreateSprite(pD3DDevice, &Sprite); //the problem
g_pD3DDevice = pD3DDevice;
if (m_flashPlayer)
m_flashPlayer->ResizePlayer(newWidth, newHeight);
for (int i = 0; i < num_textures_in_rotation; ++i)
{
hr = pD3DDevice->CreateTexture(newWidth, newHeight, 1, 0,
transparency_mode ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8, D3DPOOL_SYSTEMMEM, &g_texturesRotation[i], NULL);
if (FAILED(hr))
return false;
}
recreatedTargets = true;
return true;
}
Link error 2
D3DXMatrixTransformation2D(&Mat, NULL, 0, &Scaling, NULL, 0, &Translation); // The problem
The Last link error
FlashManager::FlashManager()
{
engine->GetScreenSize(w, h);
// Flash init
m_flashDX = GetFlashToDirectXInstance(); //the problem
m_flashPlayer = m_flashDX->CreatePlayer(w, h);
if (!m_flashPlayer)
{
MessageBox(NULL, "Flash Player failed to initialize.", "Error", MB_OK);
abort();
}
m_playerASI = new ASInterface(m_flashPlayer);
I found this email program and I can't get it to run. I am using visual studio 2013 c++. I would take any other programs too if you know of any. All I need is to be able to put this in my existing code to email a number to a gmail account. My error is:
error:
1>------ Build started: Project: sending email, Configuration: Debug Win32 ------
1>cl : Command line warning D9007: '/Gm' requires '/Zi or /ZI'; option ignored
1> Source.cpp
1>c:\users\kyle\documents\visual studio 2013\projects\sending email\sending email\source.cpp(127): warning C4715: 'MailIt' : not all control paths return a value
1>Source.obj : error LNK2019: unresolved external symbol _closesocket#4 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _connect#12 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _htons#4 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _recv#16 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _send#16 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _socket#12 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _gethostbyname#4 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _WSAStartup#8 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>Source.obj : error LNK2019: unresolved external symbol _WSACleanup#0 referenced in function "int __cdecl MailIt(char *,char *,char *,char *,char *)" (?MailIt##YAHPAD0000#Z)
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>C:\Users\kyle\documents\visual studio 2013\Projects\sending email\Debug\sending email.exe : fatal error LNK1120: 10 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
code:
#include <windows.h>
#include <stdio.h>
#include <winuser.h>
#include <windowsx.h>
#include <time.h>
/*If you don't know the mail exchange server for an address for the following
"nslookup -querytype=mx gmail.com" but replace gmail.com with the domain for
whatever email address you want. YOU MUST CHANGE THESE SETTINGS OR
IT WILL NOT WORK!!! */
#define BUFSIZE 800
#define waittime 500
#define cmailserver "gmail-smtp-in.l.google.com"
#define cemailto "kmtompkinscode#gmail.com"
#define cemailfrom "kmtompkinscode#gmail.com"
#define LogLength 100
#define SMTPLog "smtp.log"
#define cemailsubject "pin"
int MailIt(char *mailserver, char *emailto, char *emailfrom, char *emailsubject,
char *emailmessage)
{
SOCKET sockfd;
WSADATA wsaData;
FILE *smtpfile;
#define bufsize 300
int bytes_sent; /* Sock FD */
int err;
struct hostent *host; /* info from gethostbyname */
struct sockaddr_in dest_addr; /* Host Address */
char line[1000];
char *Rec_Buf = (char*)malloc(bufsize + 1);
smtpfile = fopen(SMTPLog, "a+");
if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR) {
fputs("WSAStartup failed", smtpfile);
WSACleanup();
return -1;
}
if ((host = gethostbyname(mailserver)) == NULL) {
perror("gethostbyname");
exit(1);
}
memset(&dest_addr, 0, sizeof(dest_addr));
memcpy(&(dest_addr.sin_addr), host->h_addr, host->h_length);
/* Prepare dest_addr */
dest_addr.sin_family = host->h_addrtype; /* AF_INET from gethostbyname */
dest_addr.sin_port = htons(25); /* PORT defined above */
/* Get socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
/* Connect !*/
fputs("Connecting....\n", smtpfile);
if(connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) == -1){
perror("connect");
exit(1);
}
Sleep(waittime);
err = recv(sockfd, Rec_Buf, bufsize, 0); Rec_Buf[err] = '\0';
fputs(Rec_Buf, smtpfile);
strcpy(line, "helo me.somepalace.com\n");
fputs(line, smtpfile);
bytes_sent = send(sockfd, line, strlen(line), 0);
Sleep(waittime);
err = recv(sockfd, Rec_Buf, bufsize, 0); Rec_Buf[err] = '\0';
fputs(Rec_Buf, smtpfile);
strcpy(line, "MAIL FROM:<");
strncat(line, emailfrom, strlen(emailfrom));
strncat(line, ">\n", 3);
fputs(line, smtpfile);
bytes_sent = send(sockfd, line, strlen(line), 0);
Sleep(waittime);
err = recv(sockfd, Rec_Buf, bufsize, 0); Rec_Buf[err] = '\0';
fputs(Rec_Buf, smtpfile);
strcpy(line, "RCPT TO:<");
strncat(line, emailto, strlen(emailto));
strncat(line, ">\n", 3);
fputs(line, smtpfile);
bytes_sent = send(sockfd, line, strlen(line), 0);
Sleep(waittime);
err = recv(sockfd, Rec_Buf, bufsize, 0); Rec_Buf[err] = '\0';
fputs(Rec_Buf, smtpfile);
strcpy(line, "DATA\n");
fputs(line, smtpfile);
bytes_sent = send(sockfd, line, strlen(line), 0);
Sleep(waittime);
err = recv(sockfd, Rec_Buf, bufsize, 0); Rec_Buf[err] = '\0';
fputs(Rec_Buf, smtpfile);
Sleep(waittime);
strcpy(line, "To:");
strcat(line, emailto);
strcat(line, "\n");
strcat(line, "From:");
strcat(line, emailfrom);
strcat(line, "\n");
strcat(line, "Subject:");
strcat(line, emailsubject);
strcat(line, "\n");
strcat(line, emailmessage);
strcat(line, "\r\n.\r\n");
fputs(line, smtpfile);
bytes_sent = send(sockfd, line, strlen(line), 0);
Sleep(waittime);
err = recv(sockfd, Rec_Buf, bufsize, 0); Rec_Buf[err] = '\0';
fputs(Rec_Buf, smtpfile);
strcpy(line, "quit\n");
fputs(line, smtpfile);
bytes_sent = send(sockfd, line, strlen(line), 0);
Sleep(waittime);
err = recv(sockfd, Rec_Buf, bufsize, 0); Rec_Buf[err] = '\0';
fputs(Rec_Buf, smtpfile);
fclose(smtpfile);
#ifdef WIN32
closesocket(sockfd);
WSACleanup();
#else
close(sockfd);
#endif
}
I guess the problem is that in the project setting->C/C++->General Treat Warnings as Errors was set to "Yes".
To solve it you can set it to "No", And add in project setting->C/C++->Preprocessor in Preprocessor definitions the _CRT_SECURE_NO_WARNINGS
EDIT
this link can also help:
First of all, I know this question is all over this site but I have looked at almost all of them and can't seem to find out what is wrong. This is in VS 2012. Thanks.
//Socket.h
#pragma once
#include <iostream>
#include <WinSock2.h>
using namespace std;
const int STRLEN = 256;
class Socket
{
protected:
WSADATA wsaData;
SOCKET mySocket;
SOCKET myBackup;
SOCKET acceptSocket;
sockaddr_in myAddress;
public:
Socket();
~Socket();
bool SendData( char* );
bool RecvData( char*, int );
void CloseConnection();
void GetAndSendMessage();
};
class ServerSocket : public Socket
{
public:
void Listen();
void Bind( int port );
void StartHosting( int port );
};
class ClientSocket : public Socket
{
public:
void ConnectToServer( const char *ipAddress, int port );
};
Here's Socket.cpp
//Socket.cpp
#include "stdafx.h"
#include "Socket.h"
Socket::Socket()
{
if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
{
cerr<<"Socket Initialization: Error with WSAStartup\n";
system("pause");
WSACleanup();
exit(10);
}
//Create a socket
mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( mySocket == INVALID_SOCKET )
{
cerr<<"Socket Initialization: Error creating socket"<<endl;
system("pause");
WSACleanup();
exit(11);
}
myBackup = mySocket;
}
Socket::~Socket()
{
WSACleanup();
}
bool Socket::SendData( char *buffer )
{
send( mySocket, buffer, strlen( buffer ), 0 );
return true;
}
bool Socket::RecvData( char *buffer, int size )
{
int i = recv( mySocket, buffer, size, 0 );
buffer[i] = '\0';
return true;
}
void Socket::CloseConnection()
{
//cout<<"CLOSE CONNECTION"<<endl;
closesocket( mySocket );
mySocket = myBackup;
}
void Socket::GetAndSendMessage()
{
char message[STRLEN];
cin.ignore();//without this, it gets the return char from the last cin and ignores the following one!
cout<<"Send > ";
cin.get( message, STRLEN );
SendData( message );
}
void ServerSocket::StartHosting( int port )
{
Bind( port );
Listen();
}
void ServerSocket::Listen()
{
//cout<<"LISTEN FOR CLIENT..."<<endl;
if ( listen ( mySocket, 1 ) == SOCKET_ERROR )
{
cerr<<"ServerSocket: Error listening on socket\n";
system("pause");
WSACleanup();
exit(15);
}
//cout<<"ACCEPT CONNECTION..."<<endl;
acceptSocket = accept( myBackup, NULL, NULL );
while ( acceptSocket == SOCKET_ERROR )
{
acceptSocket = accept( myBackup, NULL, NULL );
}
mySocket = acceptSocket;
}
void ServerSocket::Bind( int port )
{
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr( "0.0.0.0" );
myAddress.sin_port = htons( port );
//cout<<"BIND TO PORT "<<port<<endl;
if ( bind ( mySocket, (SOCKADDR*) &myAddress, sizeof( myAddress) ) == SOCKET_ERROR )
{
cerr<<"ServerSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(14);
}
}
void ClientSocket::ConnectToServer( const char *ipAddress, int port )
{
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr( ipAddress );
myAddress.sin_port = htons( port );
//cout<<"CONNECTED"<<endl;
if ( connect( mySocket, (SOCKADDR*) &myAddress, sizeof( myAddress ) ) == SOCKET_ERROR )
{
cerr<<"ClientSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(13);
}
}
And here's stdafx.h
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
#include "Socket.h"
And here are my error messages:
1>------ Build started: Project: Client, Configuration: Debug Win32 ------
1> stdafx.cpp
1> Socket.cpp
1> Client.cpp
1> Generating Code...
1>Socket.obj : error LNK2019: unresolved external symbol __imp__accept#12 referenced in function "public: void __thiscall ServerSocket::Listen(void)" (?Listen#ServerSocket##QAEXXZ)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__bind#12 referenced in function "public: void __thiscall ServerSocket::Bind(int)" (?Bind#ServerSocket##QAEXH#Z)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__closesocket#4 referenced in function "public: void __thiscall Socket::CloseConnection(void)" (?CloseConnection#Socket##QAEXXZ)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__connect#12 referenced in function "public: void __thiscall ClientSocket::ConnectToServer(char const *,int)" (?ConnectToServer#ClientSocket##QAEXPBDH#Z)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__htons#4 referenced in function "public: void __thiscall ServerSocket::Bind(int)" (?Bind#ServerSocket##QAEXH#Z)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__inet_addr#4 referenced in function "public: void __thiscall ServerSocket::Bind(int)" (?Bind#ServerSocket##QAEXH#Z)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__listen#8 referenced in function "public: void __thiscall ServerSocket::Listen(void)" (?Listen#ServerSocket##QAEXXZ)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__recv#16 referenced in function "public: bool __thiscall Socket::RecvData(char *,int)" (?RecvData#Socket##QAE_NPADH#Z)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__send#16 referenced in function "public: bool __thiscall Socket::SendData(char *)" (?SendData#Socket##QAE_NPAD#Z)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__socket#12 referenced in function "public: __thiscall Socket::Socket(void)" (??0Socket##QAE#XZ)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__WSAStartup#8 referenced in function "public: __thiscall Socket::Socket(void)" (??0Socket##QAE#XZ)
1>Socket.obj : error LNK2019: unresolved external symbol __imp__WSACleanup#0 referenced in function "public: __thiscall Socket::Socket(void)" (??0Socket##QAE#XZ)
1>C:\Users\ajayp_000\documents\visual studio 2012\Projects\Client\Debug\Client.exe : fatal error LNK1120: 12 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
The problem is you are not linking against the Ws2_32.lib library. To fix this you can add that to your additional dependencies tab of linker/Input settings for your project. Alternatively (as pointed out by SChepurin in the comments) you can add
#pragma comment(lib, "Ws2_32.lib")
to a source file of your project.
Another way is that click right in your project in visual studio and go to following path and add "Ws2_32.lib" in that.
Linker>Input> Additional Dependencies
Add runtimeobject.lib to the linker Additional Dependencies (in the project property page, under Linker->Input).
Even though this is a linker error. the problem can also occur if you set wrong "Runtime Library" option in
Properties > Configuration properties > C/C++ > Code Generation > Runtime Library
both called binary and calling binary should have the same values
if the property in the calling binary is MTd, then it should be MTd
in called binary.
if the property in the calling binary is MDd, then it should be MDd in called binary.
I'm trying to follow Riemer's DirectX with C++ tutorial.
I have made a few changes, for example here I have made my InitializeDevice() function in a separate file (tdirect.cpp / tdirect.h).
When I press F5 to compile and run, the program works perfectly. But when I make a change to a value (e.g. 0xff00ffff to 0xff0000ff - cyan to blue) without choosing the "Rebuild" option I get a stream of errors in my console which prevent me from compiling the program. This is pretty annoying as you can imagine. It's as if it's compiling tdirect.cpp twice.
Here's the source code of tdirect.cpp, tdirect.h, and the relevant part from main.cpp (tdirect.h is only included from main.cpp, and basicvertex.h is only included from tdirect.cpp)
tdirect.cpp:
#include "tdirect.h"
#include "basicvertex.h"
IDirect3D9 *pD3D;
D3DPRESENT_PARAMETERS D3DParams;
LPDIRECT3DDEVICE9 InitializeDevice(HWND Wnd)
{
pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (pD3D == NULL)
{
MessageBox(Wnd, "DirectX is not installed.", "No DirectX!", MB_OK);
return NULL;
}
ZeroMemory(&D3DParams, sizeof(D3DPRESENT_PARAMETERS));
D3DParams.Windowed = TRUE;
D3DParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
D3DParams.BackBufferFormat = D3DFMT_UNKNOWN;
LPDIRECT3DDEVICE9 pDevice;
if (FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Wnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &D3DParams, &pDevice)))
{
if (FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, Wnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &D3DParams, &pDevice)))
{
MessageBox(Wnd, "Failed to create reference device.", "No software device!", MB_OK);
}
else {
MessageBox(Wnd, "Falling back to software mode.", "No hardware device!", MB_OK);
}
}
return pDevice;
}
LPDIRECT3DVERTEXBUFFER9 vBuffer;
void Init(LPDIRECT3DDEVICE9 pDevice)
{
BASICVERTEX Vertices[3];
Vertices[0].x = 150;
Vertices[0].y = 100;
Vertices[0].weight = 1;
Vertices[0].colour = 0xffff0000;
Vertices[1].x = 350;
Vertices[1].y = 100;
Vertices[1].weight = 1;
Vertices[1].colour = 0xff00ff00;
Vertices[2].x = 250;
Vertices[2].y = 300;
Vertices[2].weight = 1;
Vertices[2].colour = 0xff00ffff;
if (FAILED(pDevice->CreateVertexBuffer(sizeof(BASICVERTEX)*3, 0, D3DFVF_XYZRHW | D3DFVF_DIFFUSE, D3DPOOL_DEFAULT, &vBuffer, NULL)))
{
MessageBox(NULL, "Failed to create vertex buffer", "Fail", MB_OK);
}
else {
void* pVertices;
if (FAILED(vBuffer->Lock(0, sizeof(BASICVERTEX)*3, (void**)&pVertices, 0)))
{
MessageBox(NULL, "Failed to lock vertex buffer", "Fail", MB_OK);
}
else {
memcpy(pVertices, Vertices, sizeof(BASICVERTEX)*3);
vBuffer->Unlock();
}
}
}
void DrawScene(LPDIRECT3DDEVICE9 pDevice)
{
pDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
pDevice->BeginScene();
pDevice->SetStreamSource(0, vBuffer, 0, sizeof(BASICVERTEX));
pDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
pDevice->EndScene();
pDevice->Present(NULL, NULL, NULL, NULL);
}
tdirect.h:
#pragma once
#include <Windows.h>
main.cpp include part:
#include <Windows.h>
#include "dxheader.h"
#include "tdirect.cpp"
Compiler Errors:
1>Debug\tdirect.obj : warning LNK4042: object specified more than once; extras ignored
1>main.obj : error LNK2005: "struct IDirect3DDevice9 * __cdecl InitializeDevice(struct HWND__ *)" (?InitializeDevice##YAPAUIDirect3DDevice9##PAUHWND__###Z) already defined in tdirect.obj
1>main.obj : error LNK2005: "void __cdecl Init(struct IDirect3DDevice9 *)" (?Init##YAXPAUIDirect3DDevice9###Z) already defined in tdirect.obj
1>main.obj : error LNK2005: "void __cdecl DrawScene(struct IDirect3DDevice9 *)" (?DrawScene##YAXPAUIDirect3DDevice9###Z) already defined in tdirect.obj
1>main.obj : error LNK2005: "struct IDirect3DVertexBuffer9 * vBuffer" (?vBuffer##3PAUIDirect3DVertexBuffer9##A) already defined in tdirect.obj
1>main.obj : error LNK2005: "struct _D3DPRESENT_PARAMETERS_ D3DParams" (?D3DParams##3U_D3DPRESENT_PARAMETERS_##A) already defined in tdirect.obj
1>main.obj : error LNK2005: "struct IDirect3D9 * pD3D" (?pD3D##3PAUIDirect3D9##A) already defined in tdirect.obj
1>C:\Users\me\Documents\Visual Studio 2010\Projects\DirectX\Debug\DXStuff.exe : fatal error LNK1169: one or more multiply defined symbols found
Thanks in advance :)
You're including an implementation file from your main.cpp, so it's adding the functions in again. You can't do this:
#include "tdirect.cpp"
Instead you need to create a header file with the function prototypes so you can reference them...
Do you have these defined in your "tdirect.h" (this is what main.cpp should be including)?
LPDIRECT3DDEVICE9 InitializeDevice(HWND Wnd);
etc...