Quantcast
Channel: Visual C forum
Viewing all 15302 articles
Browse latest View live

Visual C++ 2005 and 2008 generating invalid code with /O2

$
0
0

We compile our project with x64 compiler of VS2005 and 2008. For both we have installed the available ServicePacks and some HotFixes. We have had a bug and an analysis shows us that the x64 compiler generates wrong code with compiler option /O2.

We tried to create a simple app to demonstrate the wrong compilation result. Here it is:

#include "stdio.h"

// just an external function...
// returns e.g. 4
int GetValue();

void main(int argc, char* argv[])
{
    int nb = GetValue();

    for ( int i = 0; i < nb; i++)
    {
        int pos = i*2+1;
        if (!(pos >= 0))
            printf( "You will never see this message!\n");
    }
}


I compile it with x64 cross compiler: cl /c /O2 test.cpp

This generates just the resulting object file. With dumpbin /DISASM test.objwe can have a look for assembly code.

  0000000000000000: 48 89 5C 24 08     mov         qword ptr [rsp+8],rbx
  0000000000000005: 57                 push        rdi
  0000000000000006: 48 83 EC 20        sub         rsp,20h
  000000000000000A: E8 00 00 00 00     call        ?GetValue@@YAHXZ
  000000000000000F: 33 DB              xor         ebx,ebx
  0000000000000011: 8B F8              mov         edi,eax
  0000000000000013: 85 C0              test        eax,eax
  0000000000000015: 7E 17              jle         000000000000002E
  0000000000000017: 83 FB 01           cmp         ebx,1
  000000000000001A: 7D 0C              jge         0000000000000028
  000000000000001C: 48 8D 0D 00 00 00  lea         rcx,[??_C@_0CK@GKDIKOJA@You?5will?5never?5see?5this?5message?$CB@]
                    00
  0000000000000023: E8 00 00 00 00     call        printf
  0000000000000028: FF C3              inc         ebx
  000000000000002A: 3B DF              cmp         ebx,edi
  000000000000002C: 7C E9              jl          0000000000000017
  000000000000002E: 33 C0              xor         eax,eax
  0000000000000030: 48 8B 5C 24 30     mov         rbx,qword ptr [rsp+30h]
  0000000000000035: 48 83 C4 20        add         rsp,20h
  0000000000000039: 5F                 pop         rdi
  000000000000003A: C3                 ret

On line 0x17 there is a compare statement. It compares 0 with 1. Because 0 is never greater 1, the app will not jump to location 0x28. We will see the printf() message, but this should not happen, this makes no sense!

If we compile the same code without optimizer option then the app behaves as expected. If we compile with compiler of VS2012 everthing is fine with or without /O2.

Unfortunately, we cannot switch to VS2012 because we depend on third party products which are compiled with VS2005 or VS2008.

We can modify our code somehow and the generated code looks than fine. This is a workaround. This works just for a small piece of code which we know that it generates problems with optimizer. It is highly possible that more such kind of generated code exists in our product.

We are looking for a Hotfix. Is there anybody who has seen something similar? Any ideas?

Dominik.


Converting an int to an HBRUSH

$
0
0

Hi all,

How do I type-cast or convert an integer type to a HBRUSH type using C++ type-casting operators?

In C, we use something like this: HBRUSH myBrush = (HBRUSH) COLOR_WINDOW;

But in C++, we can use static_cast/dynamic_cast/reinterpret_cast/const_cast. Which among these 4 operators should I use to safely convert an int to a HBRUSH?

In tried, static_cast<HBRUSH> COLOR_WINDOW but it only produces compile-time error.

Visual C++ - 'uint64_t' : redefinition; different basic types

$
0
0

Hello,

I have a Visual C++ project that compiles fine as a 64bit platform but I get a boatload of errors similar to the following. when compiling as a 32bit platform:

<kbd>'uint64_t'</kbd> : redefinition; different basic types

I don't know where in the project that the project is still stuck on "64bit" even though I specified in the configuration manager that I need 32bit.

I will note that within my specific code itself I am not doing any typedefs and I am using open source libraries; in this case the GLM OpenGL math libraries.

I also specified the correct includes, etc. for 32bit support.

Has anyone ever seen this before?

Thank you.


Regards, Christopher K.

Code Style Checking Tool

$
0
0

Hi,

 

Are there any good free or commercial software that can check the C++ code style and find any codelines that violate a given code style specification? For example, whether the codeline is indented proplery, whether the variable is usingHungarian naming notation?

 

Thanks

How do you know what include file is required for certain functions,classes,etc?

$
0
0

Ok for example to put it simply lets say i wanted to use _getch() or any command or function,etc how an earth do i find out which header file is required?

There must be a site somewhere or some reference that details which header files are required for all the commands,functions,etc. 

msvcp120.dll missing

$
0
0

I gave a copy of a small VC++ (none managed) program I am writing to test to a friend who is missing this dll(s)
msvcp120.dll
msvcr120.dll
vccorlib120.dll
vcamp120.dll
vcomp120.dll

My friend does not have VSExpress 2013 installed, how can she get a copy of this files? and where should this files be installed?

Thanks


In the absence of clearly-defined goals, we become strangely loyal to performing daily trivia until ultimately we become enslaved by it.

httpsendrequest post not setting values

$
0
0

I read some code online on MSDN, using the same code and same php file, it doesn't work, the server response is a 200 OK, also the data is being posted but it's not being set, this is the code I have.

C++

#define _WIN32_WINNT 0x600

#include <stdio.h>
#include <wininet.h>

int main()
{
	static char hdrs[] = "Content type: application/x-www-form-urlencoded\r\n";
	static char frmdata[] = "name=test&num=2001";
	static const char *types[2] = {"*/*", NULL};
	HINTERNET hSession = InternetOpen("Mozilla",
		INTERNET_OPEN_TYPE_PRECONFIG,
		NULL,
		NULL,
		0
	);
	HINTERNET hConnect = InternetConnect(
		hSession,"127.0.0.1",
		INTERNET_DEFAULT_HTTP_PORT,
		NULL,
		NULL,
		INTERNET_SERVICE_HTTP,
		0,
		1
	);
	HINTERNET hRequest = HttpOpenRequest(
		hConnect,"POST","test/formaction.php",
		NULL,
		NULL,
		types,
		0,
		1
	);
	HttpSendRequest(
		hRequest,
		hdrs,
		strlen(hdrs),
		frmdata,
		strlen(frmdata)
	);
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hSession);
	return 0;
}

and this is the PHP code

PHP

<?php

	$id = $_POST['name'];
	$fp = fopen("data.txt", "a");
	fwrite($fp, "ID: " . $id . "\n");
	fclose($fp);

?>
it writes "ID: " to the file but no values ahead, what is wrong with this code?

Limiting maximum size of a window.

$
0
0

I wish to limit the maximum width of the main window when a user resizes the window. In the main Windows procedure I process a WM_SIZING message and then I process the WMSZ_RIGHT message from the wParam. I can put a break point there and I see that the program goes there when I drag the right hand side of the window. All good. Now the documentation says that the lParam is a pointer to a RECT structure with the current window co-ordinates as it is being dragged, and if I wish to change the size, I need to write the value to this Drag Rectangle structure. However, that is where I have come unstuck. I can't seem to translate the lParam in order to get the pointer to the Drag Rectangle.


C++/Cx arrays

$
0
0

Can one of you with experience with C++/Cx tell me why the second case here doesn’t compile:

 

#include <msclr/marshal.h>
#include
 <msclr/marshal_cppstd.h>

System
::String^ path = gcnew System::String(root);array<System::String^>^ dirs = System::IO::Directory::GetDirectories(path);
for
 (int i = 0; i < dirs->Length; i++)
{
        // this works
        System::String^ mStr = dirs[i];
        auto nativeString0(msclr::interop::marshal_as<std::string>(mStr));
        

        //this doesn't
        auto nativeString1(msclr::interop::marshal_as<std::string>(dirs[i]));
}


The error is:

1>ManagedConsole.cpp(23): error C2665: 'msclr::interop::marshal_as' : none of the 3 overloads could convert all the argument types
1>          C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\msclr/marshal_cppstd.h(33): could be 'std::string msclr::interop::marshal_as<std::string,System::String^>(System::String ^const&)'


1>          while trying to match the argument list '(System::String ^)'
 

 

 



Failure in IO Completion port

$
0
0

Hi,

I have a single thread that writes to multiple files based on the data it receives.Because there was some data miss in real time I went to Asynchronous I/O using I/O completion ports.But sometimes what has happened is there are NULL bytes in the middle of a file(may be because of WriteFile error or some other issue.Here is the code snippet Can anybody tell me if there is any bug in it.The logic that I have used is for the first 1000 writes I will call WriteFile directly passing overlapped object.Once it raises above 1000 I will wait for queueCompletion state and deque and use the overlapped object further.

T_VOID CParameterLogging::WriteToFile(HANDLE dest_file, const CString str_FileInfo,int file_identifier)
{	
	length = str_FileInfo.GetLength();
	LPOVERLAPPED ppo = NULL;
	ULONG pdwNumBytes;
	ULONG_PTR pCompKey;
	unsigned int index = 0;
	if(buffer_filled)//initally FALSE
	{		
		if(GetQueuedCompletionStatus(m_ioPort, &pdwNumBytes, &pCompKey, &ppo, 
		                                            INFINITE))	

		{	
			
			index = ppo - m_overLappedObj;  //get overlapped index where m_overLappedObj is any array of 1000
			/* Zero Memmory overlapped object*/
			ZeroMemory(&m_overLappedObj[index],sizeof(OVERLAPPED));
		}
		else
		{
			DWORD err=GetLastError();
			CString str;
			str.Format(_T("Error %d occured"),err);
			AfxMessageBox(str);

		}
	}
	else
	{
		if(counter >= M_NO_OVERLAPPED_STRUICTURES - 1)
			buffer_filled = TRUE;
		counter++;
		ppo = m_overLappedObj + counter-1;//use one of the available buffer and overlapped structure
		//printf("%X\n",ppo);
		index = counter-1;
	}

	ppo->Offset = m_fileOffsetVal[file_identifier];
	strcpy(mp_buffer[index],CT2A(str_FileInfo));

	
	int write_count = 0;
	DWORD error;
	while(write_count < 5)
	{
		if(!WriteFile(dest_file,mp_buffer[index],length,&written,ppo))
		{
			write_count++;
			error = GetLastError();
			if(error != ERROR_IO_PENDING)
			{
				Sleep(1);
				continue;
			}
			else
			{
				m_fileOffsetVal[file_identifier]+=length;
				break;
			}
		}
		else
		{
			m_fileOffsetVal[file_identifier]+=length;
			break;
		}
	}	
}

 


Amrut.s.a

Error

$
0
0

#include<iostream>
using namespace std;
int main ()
{
    cout<<"Hello World. ">>
        return 0;
}

error c2059: syntax error :'return'

MFC C++ XML Parse - Using MSXML.

$
0
0

Good day,

I got stuck to this part of the feature I am designing can you please help?

Here is my XML Code:

<tables><table name="Stamps.0409"><row index="1" ><column>1st Class Letter</column><column>(Up to 100g)</column><column>60p</column><column>stampbutton1.png</column></row><row index="2" ><column>2nd Class Letter</column><column>(Up to 100g)</column><column>50p</column><column>stampbutton2.png</column></row></table></tables>


Here is my Method:

//log
	_bstr_t logData;
	_bstr_t logAttribute;
	//Attribute variables
	_variant_t vValue;
	BSTR bstrAttributeName = ::SysAllocString(_T("row"));
	IXMLDOMElement *pIDOMElement = NULL;
	IXMLDOMNodeList *pIDOMNodeList = NULL;
	IXMLDOMNode *pIDOMNode = NULL;
	BSTR bstrItemText = NULL;
	long value = 0;
	HRESULT hResult = CoInitialize(NULL);
	if(SUCCEEDED(hResult))
	{
		try{
			MSXML2::IXMLDOMDocumentPtr XMLToRead;
			MSXML2::IXMLDOMNodeListPtr NodeListPtr;
			MSXML2::IXMLDOMNodePtr NodeRowPtr, NodeIndexPtr, NodeTablePtr, NodeNamePtr;
			hResult = XMLToRead.CreateInstance(__uuidof(MSXML2::DOMDocument40), NULL, CLSCTX_INPROC_SERVER);
			//TODO:PLACE LOG and TEST.
			if(XMLToRead->load(cXMLFile) != VARIANT_TRUE)
			{
				trace(L6,_T("XMLDataReader: Failed to Read Data on XML"));
			}
				trace(L6,_T("XMLDataReader: Successful Read Data on XML"));

				//load xml
				_variant_t varXml(cXMLFile);
				_variant_t varOut((bool)TRUE);
				varOut = XMLToRead->load(cXMLFile);
				if((bool)varOut == FALSE)
				throw(0);

				ofstream logfile;
				logfile.open("c:\\UKPostOfficeStampDat.log");
				NodeListPtr =  XMLToRead->getElementsByTagName("column");
				//Attribute
				//Table
				NodeTablePtr = XMLToRead->selectSingleNode("//table");
				NodeNamePtr = NodeTablePtr->attributes->getNamedItem("name");
				//Row
				NodeRowPtr = XMLToRead->selectSingleNode("//row");
				NodeIndexPtr = NodeRowPtr->attributes->getNamedItem("index");

				string logAtt = _bstr_t(NodeIndexPtr->nodeValue);
				string logTable = _bstr_t(NodeNamePtr->nodeValue);
				logfile<<logTable<<","<<logAtt<<",";
				for(int i = 0; i < NodeListPtr->length; i++)
				{
					logData = NodeListPtr->Getitem(i)->text;
					logfile<<(string)logData<<",";
				}	
				logfile.close();

				trace(L6,_T("XMLDataReader: Successful Write Data on log"));

			
		}
		catch(_com_error &e)
		{
			trace(L6,_T("XMLDataReader: ERROR: %ws"), e.ErrorMessage());
		}
		CoUninitialize();

	}

This is my output code:

Stamps.0409,1,1st Class Letter,(Up to 100g),60p,stampbutton.png,1st Class Letter,(Up to 100g),60p,stampbutton.png,

It seems like I have only the first part of the XML data

What I want to do is this:

Stamps.0409,1,1st Class Letter,(Up to 100g),60p,stampbutton.png,2,2nd Class Letter,(Up to 100g),50p,stampbutton2.png,

since there is row 2. It should have a 2 before the 2nd XML data.

Thanks,

MessageBox, what are the Parameters i can use to make it modal?, Do i need to mention first parameter as NULL? or by default it is NULL?

$
0
0

Hi,

I have many MessageBox() calls in my application and most of them are not modal, i want to make them modal(because my application was crashing when the user access other windows without responding to alert).

I want the user to response to the alert first, and i don't want the user to touch any other opened windows of the same application. 

For example : MessageBox(Getwindow(), msg, title, MB_OK|MB_ICONWARNING)

To make it modal,Making First parameter NULL is enough? and i read that by default it ll consider as NULL, is that correct?

and also I'm changing all AfxMessageBox() calls to MessageBox().

among MessageBox( msg, title, MB_OK|MB_ICONWARNING|MB_TASKMODAL) and MessageBox(NULL, msg, title, MB_OK|MB_ICONWARNING|MB_TASKMODAL) which one best matches my requirements?

since i'm changing in many places(many hundreds) i don't want myself in trouble after change. :) 

It might be simple question but i need suggestions.

TIA,



vc 2010

$
0
0

recently ,i feel the copiler of vc 2010 is slow,whether should  i update it to the vc 2013?

Problem concatenating strings

$
0
0

Hello,

I am trying to concatenate  a string, followed by a pointer to a string, followed by another string. I cannot work out how to do this. The code is shown below:

void ChristianSettings(SOCKET TCPsock, char *value)
{  
	sendSCPI(TCPsock, "frequency:mode fixed\n");
	sendSCPI(TCPsock, "frequency" + &value + "\n");
..........
int sendSCPI(int sd, char *pBuffer)
{
	unsigned int nLen;
		nLen = send(sd, pBuffer, strlen(pBuffer), 0);
		if (nLen != strlen(pBuffer))
	{
		printf("Error writing to socket. Len = %d\n", nLen);
	}
	return nLen;

I have tried searching the internet, but all the solutions to similar problems don't seem tow ork for me eg one solution suggested using msg += string("blah")+string(value)+string("blah") but i got an error saying the += operator was not recognised (I know this is a seperate issue and most likely due to me missing a header file, perhaps?). Anyone have any ideas of how I can overcome this problem? Thanks in advance for any help!

Christian


Visual C++ - 'uint64_t' : redefinition; different basic types

$
0
0

Hello,

I have a Visual C++ project that compiles fine as a 64bit platform but I get a boatload of errors similar to the following. when compiling as a 32bit platform:

<kbd>'uint64_t'</kbd> : redefinition; different basic types

I don't know where in the project that the project is still stuck on "64bit" even though I specified in the configuration manager that I need 32bit.

I will note that within my specific code itself I am not doing any typedefs and I am using open source libraries; in this case the GLM OpenGL math libraries.

I also specified the correct includes, etc. for 32bit support.

Has anyone ever seen this before?

Thank you.


Regards, Christopher K.

Object changing when calling methods.

$
0
0

I am pulling my hair out with what seems to me as a very weird behavior. (Using VS 2013 Premium).

I have a TDatabase class which has a *TDatabasePimpl.  When I instantiate the class.

TDatabase db();

It sets some attributes in the pimpl including setting a *SQLHSTMT db.

When I call a method (immediately after instantiating the db object) the object is the same as it enters the method, but after stepping into the code the data in the pimpl changes and my *SQLHSMT changes to 0xCCCCCCCCC.

What am I doing wrong?

Below Watch on the TDatabase immediately after instantiating.

TDatabase db(); 

db.pimpl->db = 0x0016dfe8 and that points to the SQLHSTMT at 0x00322fe8

[Image removed as I am unverified (still waiting for verification email)]

this                                      0x0016e564 {env=0x0016e1f0 {0x00321a20} pimpl=0x0058c470 {db=0x0016dfe8 {0x00322fe8}

   env                                   0x0016e1f0 {0x00321a20}

   pimpl                                0x0058c470 {db=0x0016dfe8 {0x00322fe8} res=0x00000000 {???}


I then call 

db.query("select * from mytable");

The code enters the db.query method:

[Image removed so 2 image per post can be followed.] Image looked like this and showed that control was at the opening {:

bool TDatabase::query(const char *query, ...)

{

     va_list ap;

     sstring buf;

[Image removed so 2 images per post rule can be followed] It showed the memory addresses, and looked almost identicl to the image above, but db was replaced with this

this->pimpl->db = 0x0016dfe8 and that points to the SQLHSTMT at 0x00322fe8 (NOTHING HAS CHANGED).

But as soon as I step once into my code it does change.

[Image removed as I am unverified? (Still waiting for verification email)]

Looks like this:

this                                      0x0016e564 {env=0x0016e1f0 {0xcccccccc} pimpl=0x0058c470 {db=0x0016dfe8 {0xccccccc}

   env                                   0x0016e1f0 {0xcccccccc}

   pimpl                                0x0058c470 {db=0x0016dfe8 {0xcccccccc} res=0x00000000 {???}


As you can see this still points to 0x0016e564

env still points to 0x0016e1f0

and pimpl still points to 0x0058c470

this->pimpl->db points to 0x0016dfe8

But the value that env points to, and the value that this->piml->db have both changed to 0xcccccccc 



I hope I am simply forgetting to do something simple. What is happening?



Thanks!

How to get Case Sensitive Filename/Path in MFC

$
0
0

Hi,

I need to get the Case sensitive Filename and Path to chek if the filename described in an XML file and the file on hard drive match.

I have searched the web and tried many suggestions, but they all did not work. They just returned the filename as given as argument to such functions.

At the moment I split the path by '\' and use 

DWORD result  = SHGetFileInfo(testPath.c_str(), 0, &sfi, sizeof(sfi), SHGFI_DISPLAYNAME);

for each part of the path to check, and in this way I build up a new string from 

sfi.szDisplayName
which I compare with the string I read from XML file.

This works as long as in "Folder Options" -> "View" the option "Hide extensions for known file types" is unchecked. If checked, sfi.szDisplayName does not contain the extension.

What can I do to read the case sensitive filename, extension and path as stored on the hard drive, or is there a function that returns the filename / path as stored on hard drive?

"Hacking" the file system to be case sensitive is not a solution.

BR,

Thorsten

[VS2013] Linkning library project order

$
0
0

Hello %User%!

I have:

1) project of static library - "Test1", which contains only 1 header file with:

namespace OpenGL
{
    extern "C" __declspec(dllimport) void* __stdcall wglGetProcAddress(char* FunctionName);
}

and in Properties set Additional Dependencies = "OpenGL32.lib"

2) project of console programm - "Test2" with:

#include "Test1/Header.h"

int main(int argc, char* argv[])
{
    OpenGL::wglGetProcAddress("Test");

    return 0;
}

and in Properties set Additional Dependencies = empty, Referced = Test1 [with Link Library Dependencies and Use Library Dependency Inputs]

When compiling this thing we have:

Error	1	error LNK2019: unresolved external symbol __imp__wglGetProcAddress@4 referenced in function _main	Test2\Test2\Test2.obj	Test2
Error	2	error LNK1120: 1 unresolved externals	Test2\Debug\Test2.exe	Test2

If In Test1 add custom function like wwglGetProcAddress, which call original API functionThen nothing happened, error again.

If at Test1 or at Test2 add #pragma comment(lib, "OpenGL32.lib")Then perfectly works

If at Test1 added Additional Dependency += OpenGL32.lib Then perfectly works

It seems, like a project Test2 not use Additional Dependencies from Test2.
By that i think image of processing like -> Image

Anybody knows how to do like -> Image ?
So linker grab Additional Dependencies from all depended project then linking? or grab dependencies of linking project for linking project, but not only from main project when linking depended project. Something like that...

Thanks for looking and help!

ERROR : "Run-Time Check Failure #3 - The variable 'number3' is being used without being initialized

$
0
0

My new to programming and I keep on getting these two errors when I try and run the code. "Run-Time Check Failure #3 - The variable 'number3' is being used without being initialized, and "Run-Time Check Failure #2 - The variable 'number2' is being used without being initialized. Can someone tell me what I did wrong, I've tried looking online and my textbook but I can't see it and also if you see any other error please tell me. Thank you and this is my code

#include<iostream>//
using std::cout;//
using std::endl;//
using std::cin;//
int main()
{
int number1;// first integer read form user
int number2;// second integer read from user
int number3;// third interger read from user
int smallest;// smallest interger read from user
int largest;// largest integer read from user
int sum;// sum of integers read from user
double average;// average of intergers read from user
int product;// product of integers read from user
std::cout << "input three different integers:";//
cin >> number1 >> number2 >> number3;
largest = number1; // assume first integer is largest
if (number2 > largest );
cout << number2 << ">"<< largest << endl;
if ( number3 > largest );
cout << number3;
number3 = largest;
smallest = number1; // assume first integer is smallest
if (number2 < smallest );
cout << number2 << "<"<< smallest << endl;
if ( number3 < smallest );
cout << number3
number3 = smallest;
std::cout << "the answers are: ";
cout << "largest = "<< largest
<<"smallest = "<< smallest
<< "sum = "<< number1 + number2 + number3
<< "average = "<< (number1 + number2 +number3) /3
<< "product ="<< number1 * number2 * number3 << endl;
return 0;
}
// end main

Viewing all 15302 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>