question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
587,703
596,743
Windows API: Detecting when a driver install has finished
I'm writing some software that automatically connects a Bluetooth device using the Windows Bluetooth API. When it connects, Windows automatically starts installing the Bluetooth HID device driver, as expected: This takes about 10-15 seconds, after which Windows displays the familar "ready for use" message: The proble...
You might want to have a look at this sample code and RegisterDeviceNotification function. I'm not sure for 100%, but it seems to work if you specify correct guid for your device class.
587,767
587,849
How to output to the console in C++/Windows
When using iostream in C++ on Linux, it displays the program output in the terminal, but in Windows, it just saves the output to a stdout.txt file. How can I, in Windows, make the output appear in the console?
Since you mentioned stdout.txt I google'd it to see what exactly would create a stdout.txt; normally, even with a Windows app, console output goes to the allocated console, or nowhere if one is not allocated. So, assuming you are using SDL (which is the only thing that brought up stdout.txt), you should follow the advi...
588,307
588,352
C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly
On Windows, clock() returns the time in milliseconds, but on this Linux box I'm working on, it rounds it to the nearest 1000 so the precision is only to the "second" level and not to the milliseconds level. I found a solution with Qt using the QTime class, instantiating an object and calling start() on it then calling ...
You could use gettimeofday at the start and end of your method and then difference the two return structs. You'll get a structure like the following: struct timeval { time_t tv_sec; suseconds_t tv_usec; } EDIT: As the two comments below suggest, clock_gettime(CLOCK_MONOTONIC) is a much better choice if you have i...
588,700
588,747
Programmer productivity with STL vs. custom utility classes
I work in an environment where, for historical reasons, we are using a hodgepodge of custom utility classes, most of which were written before STL arrived on the scene. There are many reasons why I think it is a good idea to at least write new code using STL, but the main one is that I believe it increases programmer p...
There are no studies that will show STL is more productive just because it is STL. Productivity gains from using it are due to it being a standard programmers are familiar with it, and because the code is already written and tested. If your company already has utility classes that employees are familiar with, and this ...
588,857
588,916
'Start Debugging' takes forever in VisualStudio 2005
I have a large project that has > 1000 files. When I press the green 'Play' button to start debugging, once everything is built, it can take up to 5 minutes for the app to start running. It looks like Visual Studio is loading and unloading various DLLs, but it also just sits there occasionally doing nothing. Running fr...
Some thoughts and suggestions: It could be caused by complex dependency checking that VS2005 does to ensure that no components have changes and have to be re-built prior to debugging. Sometimes tweaking the inter-project dependencies in the solution can help. Are you using source control integration in Visual Studio...
588,859
591,844
ramdisk with a file mirror
I wanted to speed up compilation so i was thinking i could have my files be build on a ramdisk but also have it flushed to the filesystem automatically and use the filesystem if there is not enough ram. I may need something similar for an app i am writing where i would like files to be cached in ram and flushed into th...
Ram-disks went the way of the dodo with the file system cache. It can make much better decisions than a static cache, having awareness of RAM usage by other programs and the position of the disk write head. The lazy write-back is for free.
589,076
589,126
When is it not a good idea to pass by reference?
This is a memory allocation issue that I've never really understood. void unleashMonkeyFish() { MonkeyFish * monkey_fish = new MonkeyFish(); std::string localname = "Wanda"; monkey_fish->setName(localname); monkey_fish->go(); } In the above code, I've created a MonkeyFish object on the hea...
One way to do this is to have your string std::string name; As the data-member of your object. And then, in the unleashMonkeyFish function create a string like you did, and pass it by reference like you showed void setName( const std::string & parameter_name ) { name = parameter_name; } It will do what you want ...
589,144
589,160
Basic Pixel/Cell Counting Algorithm
Good night :) I am currently playing with the DevIL library that allows me to load in image and check RGB values per pixel. Just as a personal learning project, I'm trying to write a very basic OCR system for a couple of images I made myself in Photoshop. I am successfully able to remove all the distortions in the imag...
The flood fill algorithm will work for counting the included pixels, as long as you have the images filtered down to simple black & white bitmaps. Having said that, you can perform character recognition by comparing each character to a set of standard images of each character in your set, measuring the similarity, and ...
589,208
589,229
Are there any reasons not to use Boost::shared_ptrs?
I've asked a couple questions (here and here) about memory management, and invariably someone suggests that I use boost::shared_ptrs. Given how useful they seem to be, I'm seriously considering switching over my entire application to use boost::shared_ptrs. However, before I jump in with both feet and do this, I want...
The downside is they're not free. You especially shouldn't use shared_ptr/shared_array when scoped_ptr/scoped_array (or plain old stack allocation) will do. You'll need to manually break cycles with weak_ptr if you have any. The vector question you link to is one case where I might reach for a shared_ptr, the second qu...
589,535
589,543
naming convention for public and private variable?
Is it wrong to use m_varname as public and the same class with _variable as private
Some concerns: Why do you have public variables? Identifiers starting with _ and __ are reserved for system libraries. In practice this doesn't matter very often, but it's nice to be aware. With those things said, there's nothing wrong with creating a naming convention, regardless of how it looks. Just be consisten...
589,836
589,857
Problem regarding OpenGL and the process of converting C to C++
Alright. So I wanted to use a file written in c in c++. I ran the code in c and had absolutely no problems. Since I don't know c, I worked with some conversion software for a while, but it wasn't effective (guessing the coding format wasn't in the style it needed). I decided to try it out myself and it looked like all ...
The first statement that doesn't give an error is an command from GLU32.DLL, the others should be OPENGL32.DLL commands. Check if you linked the libraries correctly and try to copy the DLLs in the program directory. The last line could also be some error with your ImageData, but since you said it worked in C and you on...
589,985
590,010
Vectors, structs and std::find
Again me with vectors. I hope I'm not too annoying. I have a struct like this : struct monster { DWORD id; int x; int y; int distance; int HP; }; So I created a vector : std::vector<monster> monsters; But now I don't know how to search through the vector. I want to find an ID of the monster insid...
std::find_if: it = std::find_if(bot.monsters.begin(), bot.monsters.end(), boost::bind(&monster::id, _1) == currentMonster); Or write your own function object if you don't have boost. Would look like this struct find_id : std::unary_function<monster, bool> { DWORD id; find_id(DWORD id):id(id) { } b...
590,021
590,074
Is there a cross-platform way of getting a list of running applications?
I need to get a list of applications that are currently running so that my C++ application and make them take focus. Has anybody done this?
There is no real cross platform way of doing that. The whole concept of processes, applications, etc. is an operating system specific concept. If you use a certain library to solve the issue, you are not really cross platform, you are limited to the platforms that are supported by this library. E.g. Qt is not universal...
590,027
590,042
Can I un-singleton a singleton
I want to use a library that makes heavy use of singletons, but I actually need some of the manager classes to have multiple instances. The code is open source, but changing the code myself would make updating the lib to a newer version hard. What tricks are there, if any, to force creation of a new instance of a singl...
The answer is "it depends". A good example is the C++ heap used by Microsofts C runtime. This is implemented as a singleton, of course. Now, when you statically link the CRT into multiple DLLs, you end up with multiple copies. The newer implementations have a single heap, whereas the older CRTs created one heap per lib...
590,098
590,488
Detect RPC connection loss from server-side on Windows
Is there any way to check the status of the RPC connection from the server-side? I am looking for a way to detect if the connection from the client is lost, be it client crash or other connectivity issues.
Use Context Handles for managing server state between calls for a particular client. RPC uses keep-alive's to detect client disconnects and will execute your context handle rundown routine if the client disconnects.
590,264
590,297
Is it practically safe to write static data from multiple threads
I have some status data that I want to cache from a database. Any of several threads may modify the status data. After the data is modified it will be written to the database. The database writes will always be done in series by the underlying database access layer which queues database operations in a different proce...
No, it's not safe. The code generated that does the writing to m_activityStarted and the others may be atomic, but that is not garantueed. Also, in your setters you do two things: set a boolean and make a call. That is definately not atomic. You're better off synchronizing here using a lock of some sort. For example, o...
590,362
591,442
Allocating large blocks of memory with new
I have the need to allocate large blocks of memory with new. I am stuck with using new because I am writing a mock for the producer side of a two part application. The actual producer code is allocating these large blocks and my code has responsibility to delete them (after processing them). Is there a way I can ensure...
With respect to new in C++/GCC/Linux(32bit)... It's been a while, and it's implementation dependent, but I believe new will, behind the scenes, invoke malloc(). Malloc(), unless you ask for something exceeding the address space of the process, or outside of specified (ulimit/getrusage) limits, won't fail. Even when y...
590,792
590,816
How to kill a MFC Thread?
I spawn a thread using AfxBeginThread which is just an infinite while loop: UINT CMyClass::ThreadProc( LPVOID param ) { while (TRUE) { // do stuff } return 1; } How do I kill off this thread in my class destructor? I think something like UINT CMyClass::ThreadProc( LPVOID param ) { while (m_bKillThread)...
Actively killing the thread: Use the return value of AfxBeginThread (CWinThread*) to get the thread handle (m_hThread) then pass that handle to the TerminateThread Win32 API. This is not a safe way to terminate threads though, so please read on. Waiting for the thread to finish: Use the return value of AfxBeginThread ...
590,822
590,876
Dealing with accuracy problems in floating-point numbers
I was wondering if there is a way of overcoming an accuracy problem that seems to be the result of my machine's internal representation of floating-point numbers: For the sake of clarity the problem is summarized as: // str is "4.600"; atof( str ) is 4.5999999999999996 double mw = atof( str ) // The variables us...
A very simple and effective way to round a floating point number to an integer: int rounded = (int)(f + 0.5); Note: this only works if f is always positive. (thanks j random hacker)
591,078
591,239
Can the list of C++ files in a Visual Studio project be dynamically filled?
I have a tool that generates most (but not all) files that need to be compiled in Visual Studio. The tool reads a configuration file and generates c++ files afterwards. This list can differ from one call to another when the configuration is altered. I am wondering whether it would be possible to adapt the compiling pro...
Use a pre-build step to run your tool. Also, create a file containing the list of includes and sources This file name should be fixed (so that you don't have to change project properties or the vcproj file) -- add it to the project. E.g: Project Properties > Command Line > Additional Options > @headerListingFile ...
591,338
591,349
how to declare volatile iterator in c++
Is there a way to declare an iterator which is a member variable in a class and that can be incremented using a member function even though the object of that class is const.
That would be with the "mutable" keyword. class X { public: bool GetFlag() const { m_accessCount++; return m_flag; } private: bool m_flag; mutable int m_accessCount; };
591,533
591,623
how to handle exceptions in C# DLL loaded by C++
I have a DLL that is created in C# for the purpose of providing a COM interface to a third-party C# library. I have a C++ program that uses that COM interface so that it can communicate with the C# library. Sometimes, exceptions get thrown on the C# side and all I get back on the C++ side is an HRESULT from the COM i...
There is a mapping of a managed exception to an HRESULT. Consult the table in this MSDN article. .NET retrieves error info from a COM object with IErrorInfo. That might well work the other way around too. Worth a shot.
592,067
592,073
Am I geting a structure copy here?
Here is a fake code sample vector<Fred> gFred; { // init gFred Fred &fred = gFred[0]; size_t z = 0; do { fred = gFred[z]; // do odd processing with fred z++; } while (fred.lastElementInSet == 0); } The thing that caught my attention was the fact that gFred[0] was...
Yes, you are getting a structure copy there. References cannot be rebound, i.e., they stay the same once they are initialized. And your solution is also appropriate. Dunno about smacking yourself in the head though.
592,075
592,148
why doesn't winmain set the errorlevel?
Why does this program correctly display a message box, but does not set the error level? int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, _T("This should return 90 no?"), _T("...
If your program is a Windows app, rather than a Console app, the command interpreter doesn't wait for it to complete (before you press OK, take a look at the command window and you'll see that it's ready for the next command). If this is the case, building your application as Console subsystem app would solve the probl...
592,160
592,205
static vs extern "C"/"C++"
What is the difference between a static member function and an extern "C" linkage function ? For instance, when using "makecontext" in C++, I need to pass a pointer to function. Google recommends using extern "C" linkage for it, because "makecontext" is C. But I found out that using static works as well. Am I just luck...
Yes, you are just lucky :) The extern "C" is one language linkage for the C language that every C++ compiler has to support, beside extern "C++" which is the default. Compilers may supports other language linkages. GCC for example supports extern "Java" which allows interfacing with java code (though that's quite cumbe...
592,763
592,950
Numerical range iterators in boost?
I'm aware of the range iterators in boost, and as for this reference, it seems there should be an easy way of doing what I want, but it's not obvious to me. Say I want to represent a numerical range, 0 to 100 (inclusive or not), say range(0,100). I would like to do something like: for_each(range<int>(0,100).begin(), ra...
boost::counting_iterator #include <boost/iterator/counting_iterator.hpp> std::for_each( boost::counting_iterator<int>(0), boost::counting_iterator<int>(100), do_something );
593,037
593,139
How do I iterate a collection of Excel columns in C++ using Automation?
I want to do the moral equivalent of the following VBA code: For Each col In Worksheets("Sheet1").Columns # do stuff Next col I have generated MFC wrappers for the Excel type library that get me this far (the generated types all derive from COleDispatchDriver: CApplication app; app.CreateDispatch( clsid, e ); CWo...
I assume that you're trying to traverse all the cells in the spreadsheet. You can get the active worksheet's "all cells" range, and loop through its rows and columns : CSheets sheets = book.get_WorkSheets(); CWorkSheet sheet = sheets.get_ActiveSheet(); Range cells = sheet.get_Cells(); int nRows = cells.get_Rows().get...
593,244
593,263
dumping c++ structures to a text file
how would one go about writing the contents of a structure in C++ to a text file? What I want to do is, say I have a structure called A, with data members A.one, A.two, and so on, and I want to write them out line by line into a text file, like so Structure A A.one = value A.two = value ... Structure B B.one = value B....
No reflection in C++, so you have to do it manually, eg (using iostream, for simplicty): dump_A(std::cout, "A", a); void dump_A(std::iostream& os, const char* name, A const& a) { os << "Structure " << name << '\n' << name << ".one = " << a.one << '\n' << name << ".two = " << a.two << '\n'; }
593,403
593,421
Always-in-front dialogs
Is there a way to create a modeless dialog box in C++ MFC which always stays on top of the other windows in the application? I'm thinking sort of like the Find dialog in Visual Studio 2005 - where it stays on top, but you can still edit the underlying text. (If it makes any difference, it's not MDI; it's a dialog-based...
Note: This does not work under Windows 10, and may not work under Windows 7 and 8 (Reports vary). From Nish: ###Making your dialog stay on top Haven't you seen programs which have an "always-stay-on-top" option? Well the unbelievable thing is that you can make your dialog stay on top with just one line of code. Simply...
593,608
593,612
Accessing vector elements inside another vector through an iterator?
std::vector< std::vector<coords> >::iterator iter; for(iter = characters.begin(); iter != characters.end(); iter++) { std::vector<coords>* cha = iter; // doesn't work. } // does work. std::vector<coords>* character = &characters.at(0); coords* first = &character->at(0); And I don't get why. Isn't iter supposed t...
An iterator is a type that can be dereferenced like a pointer, i.e., it has an explicit operator*() and operator->(). It doesn't have to be a pointer. So use &*iter if you want to get the address of the vector.
593,792
593,832
C++ Directory Restructuring
I have a source code of about 500 files in about 10 directories. I need to refactor the directory structure - this includes changing the directory hierarchy or renaming some directories. I am using svn version control. There are two ways to refactor: one preserving svn history (using svn move command) and the other wi...
If you're having to rewrite the #includes to do this, you did it wrong. Change all your #includes to use a very simple directory structure, at mot two levels deep and only using a second level to organize around architecture or OS dependencies (like sys/types.h). Then change your make files to use -I include paths. Vo...
594,089
594,092
Does std::vector.clear() do delete (free memory) on each element?
Consider this code: #include <vector> void Example() { std::vector<TCHAR*> list; TCHAR* pLine = new TCHAR[20]; list.push_back(pLine); list.clear(); // is delete called here? // is delete pLine; necessary? } Does list.clear() call delete on each element? I.e. do I have to free the memory before ...
No (you need to do the delete yourself at the end as you suggest in your example as the destruction of the bald pointer doesnt do anything). But you can use a boost [or other RAII-based idiom] smart pointer to make it Do The Right Thing (auto_ptr would not work correctly in a container as it has incompatible behaviour ...
594,135
594,151
What's up with static_cast with multiple arguments?
Can anyone tell me what this cast has for effect (besides setting happyNumber to 1337), if any at all, and if it has no other effect, how come I can write code like this??? Is this a compiler bug, or some "hidden away feature" of C++? int happyNumber = static_cast<int>(123.456, TRUE, "WTF" , false , "IS" , NULL , "GOIN...
Static cast takes one argument, but its argument is an expression, and expressions can include the comma operator. Comma is used in situations where you want to evaluate two or more expressions at once for their side effects, e.g.: int i, j; for (i=0, j=0; i < 10; i++,j++) { // do stuff } It's somewhat useful bec...
594,162
594,172
Intercepting/Rerouting TCP SYN packets to C++ program in linux
I am trying to find the easiest way to intercept TCP SYN packets sent by my computer in a c++ program. There are couple of options that I know. One would be monitor all traffic and just selectively work with the SYN packets doing nothing with the rest. Another option I came across was to use a packet filtering utility ...
If you merely want to see the packets, use libpcap and packet filtering - that'll work on most any UNIX variant. If you want to somehow intercept and rewrite the packets, please supply more information about what you're trying to do, and what's supposed to happen to the packets afterwards. As you suggest, that might be...
594,253
594,293
How to debug a DLL file in Delphi
I am a developer working on Visual C++, but in my project there are some Delphi components. I need to debug the Delphi components to fix some issues. What are the things that are a must to generate a DLL file in debug and then start debugging in Delphi?
In Delphi 7 you would do this: Project | Options | Compiler | Debugging | Debug information (check) Then go to Run | Parameters | Host Application and enter the name of your exe. Add some breakpoints in your DLL code and then click run. Your exe will be loaded and you can debug the DLL parts in the Delphi IDE. If your ...
594,521
594,630
STL iterator with custom template
i have the following template method, template <class T> void Class::setData( vector<T> data ) { vector<T>::iterator it; } and i'm getting the following compilation error ( XCode/gcc ) error: expected `;' before 'it' i found someone else with a similar problem here (read down to see it's the same even though...
Classic case of when to use the typename keyword. Hoping that you have #include-ed vector and iterator and have a using namespace std; somewhere in scope. Use: typename vector<T>::iterator it; Look up dependent names. Start here.
594,522
594,542
When would you use an array rather than a vector/string?
I'm a beginner C++ programmer and so I've learnt using arrays rather than vectors (this seems to be the general way to do things, then move on to vectors later on). I've noticed that a lot of answers on SO suggest using vectors over arrays, and strings over char arrays. It seems that this is the "proper" way to code in...
When writing code that should used in other projects, in particular if you target special platforms (embedded, game consoles, etc.) where STL might not be present. Old projects or projects with special requirements might not want to introduce dependencies on STL libraries. An interface depending on arrays, char* or wha...
594,703
597,288
Exporting class from executable to dll
I need in a DLL to use a class, defined in an executable (DLL and executable are compiled by the same compiler). But I don't want the source code of this class definition to be available to DLL, only declaration. One possible way to do it is to make all the necessary class methods to be virtual (so that DLL linker will...
So far as I know, it is ok to use MS VS's dllexport to export a class or function from a exe and use it in a DLL. and it runs cool if your DLL and Exe execute in one process.
594,730
594,769
Overriding static variables when subclassing
I have a class, lets call it A, and within that class definition I have the following: static QPainterPath *path; Which is to say, I'm declaring a static (class-wide) pointer to a path object; all instances of this class will now have the same shared data member. I would like to be able to build upon this class, subcl...
Use a virtual method to get a reference to the static variable. class Base { private: static A *a; public: A* GetA() { return a; } }; class Derived: public Base { private: static B *b; public: A* GetA() { return b; } }; Notice that B derives from A here. Then: void Derived::pai...
594,903
594,915
Switching to Linux for Windows development, bad idea?
I was contemplating switching to Linux for C++ development, coming from a Windows environment. Is this a bad idea? My workplace uses Windows and Visual Studio for our projects (some C# and java too, but right now I'm only developing in C++). If they decide to put me on a C# project, would development still possible (m...
That's a bad idea. I can see at least two reasons : Develop on the same OS you write software for Visual Studio rocks
595,216
595,275
regular expression to split up searchphrase
I was hoping someone could help me writing a regex for c++ that matches words in a searchphrase, and explain it bit by bit for learning purposes. What I need is a regex that matches string within " " like "Hello you all", and single words that starts/ends with * like *ack / overfl*. For the quote part I have \"[\^\\s]...
Try this regular expression: (?:\*?\w+\*?|"(?:[^\x5C"]+|\x5C(?:\x5C\x5C)*")*")+ For readability I replaced the backslash characters by \x5C. The expression "(?:[^\x5C"]+|\x5C(?:\x5C\x5C)*")*" will also match "foo \"bar\"" and other proper escaped quote sequences (but only the " might be escaped). So foo* bar *baz *quu...
595,314
595,381
parser: parsing formulas in template files
I will first describe the problem and then what I currently look at, in terms of libraries. In my application, we have a set of variables that are always available. For example: TOTAL_ITEMS, PRICE, CONTRACTS, ETC (we have around 15 of them). A clients of the application would like to have certain calculations perfor...
If you have a fixed number of variables it may be a bit overkill to invoke a parser. Though Spirit is cool and I've been wanting to use it in a project. I would probably just tokenize the string, make a map of your variables keyed by name (assuming all your variables are ints): map<const char*,int*> vars; vars["CONTRA...
595,787
597,061
What is a good scripting language to integrate into high-performance applications?
I'm a game's developer and am currently in the processing of writing a cross-platform, multi-threaded engine for our company. Arguably, one of the most powerful tools in a game engine is its scripting system, hence I'm on the hunt for a new scripting language to integrate into our engine (currently using a relatively b...
We've had good luck with Squirrel so far. Lua is so popular it's on its way to becoming a standard. I recommend you worry more about memory than speed. Most scripting languages are "fast enough" and if they get slow you can always push some of that functionality back down into C++. Many of them burn through lots of me...
596,093
596,154
C++ Etiquette about Member Variables on the Heap
Is it considered bad manners/bad practice to explicitly place object members on the heap (via new)? I would think you might want to allow the client to choose the memory region to instantiate the object. I know there might be a situation where heap members might be acceptable. If you know a situation could you descr...
If you have a class that's designed for copy semantics and you're allocating/deallocating a bunch of memory unnecessarily, I could see this being bad practice. In general, though, it's not. There are a lot of classes that can make use of heap storage. Just make sure you're free of memory leaks (deallocate things in ...
596,122
596,135
Template Function under GCC
Duplicate. See this. Can someone tell me why this does not compile under GCC? Both MSVC6, and VS2008 will compile it, with no warnings, even. The code... #include <iostream> #include <vector> #include <ctime> #include <cstdlib> using namespace std; template <typename T> T range(vector<T> &v) { vector<T>::iterator...
The compiler does not know enough to parse vector::iterator as a type at that point. Use the typename keyword to give it a hint: typename vector<T>::iterator i = v.begin();
596,162
596,180
Can you remove elements from a std::list while iterating through it?
I've got code that looks like this: for (std::list<item*>::iterator i=items.begin();i!=items.end();i++) { bool isActive = (*i)->update(); //if (!isActive) // items.remove(*i); //else other_code_involving(*i); } items.remove_if(CheckItemNotActive); I'd like remove inactive items immediately af...
You have to increment the iterator first (with i++) and then remove the previous element (e.g., by using the returned value from i++). You can change the code to a while loop like so: std::list<item*>::iterator i = items.begin(); while (i != items.end()) { bool isActive = (*i)->update(); if (!isActive) { ...
596,185
596,348
Is it possible to get a char* name from a template type in C++
I want to get the string name (const char*) of a template type. Unfortunately I don't have access to RTTI. template< typename T > struct SomeClass { const char* GetClassName() const { return /* magic goes here */; } } So SomeClass<int> sc; sc.GetClassName(); // returns "int" Is this possible? I can't find a w...
No and it will not work reliable with typeid either. It will give you some internal string that depends on the compiler implementation. Something like "int", but also "i" is common for int. By the way, if what you want is to only compare whether two types are the same, you don't need to convert them to a string first. ...
596,360
597,545
Good c++ lib for threading
I prefer a lib solely based on pthreads. What is a good c++ lib to for threading?
I looked at some options some time ago. Here are some: Boost Thread - This is the most standard choice. Boost is the most standard library for C++, that is not in the official standard. POCO - Has thread support and a lot more. Is my preferred choice because it lets you set thread priorities, something boost doesn't...
596,411
596,427
Simple C++ Threading
I am trying to create a thread in C++ (Win32) to run a simple method. I'm new to C++ threading, but very familiar with threading in C#. Here is some pseudo-code of what I am trying to do: static void MyMethod(int data) { RunStuff(data); } void RunStuff(int data) { //long running operation here } I want to to ...
#include <boost/thread.hpp> static boost::thread runStuffThread; static void MyMethod(int data) { runStuffThread = boost::thread(boost::bind(RunStuff, data)); } // elsewhere... runStuffThread.join(); //blocks
596,636
596,643
C++: difference between ampersand "&" and asterisk "*" in function/method declaration?
Is there some kind of subtle difference between those: void a1(float &b) { b=1; }; a1(b); and void a1(float *b) { (*b)=1; }; a1(&b); ? They both do the same (or so it seems from main() ), but the first one is obviously shorter, however most of the code I see uses second notation. Is there a difference? Maybe ...
Both do the same, but one uses references and one uses pointers. See my answer here for a comprehensive list of all the differences.
596,964
596,987
Help me make this code exception-safe
So I have this library code, see... class Thing { public: class Obj { public: static const int len = 16; explicit Obj(char *str) { strncpy(str_, str, len); } virtual void operator()() = 0; private: char str_[len]; }; explicit Thi...
Since your Thing destructor already knows how to clean up the vector, you're most of the way towards a RAII solution. Instead of creating the vector of Objs, and then passing it to Thing's constructor, you could initialize Thing with an empty vector and add a member function to add new Objs, by pointer, to the vector. ...
597,063
597,250
extend a abstract base class w/o source recompilation?
ignore this, i thought of a workaround involving header generation. It isnt the nicest solution but it works. This question is to weird to understand. Basically i want to call a virtual function that hasnt been declared in the lib or dll and use it as normal (but have it not implemented/empty func). I have an abstract...
Are you asking if you can add virtual functions to the base class without recompiling? The short answer to that is "no". The long answer is in your question, you'd have to provide some kind of generic "call_func" interface that would allow you to call functions "dynamically".
597,078
597,081
__FILE__, __LINE__, and __FUNCTION__ usage in C++
Presuming that your C++ compiler supports them, is there any particular reason not to use __FILE__, __LINE__ and __FUNCTION__ for logging and debugging purposes? I'm primarily concerned with giving the user misleading data—for example, reporting the incorrect line number or function as a result of optimization—or takin...
__FUNCTION__ is non standard, __func__ exists in C99 / C++11. The others (__LINE__ and __FILE__) are just fine. It will always report the right file and line (and function if you choose to use __FUNCTION__/__func__). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performan...
597,138
599,949
Referencing a platform-specific library from a non-specific .NET app
I often need to include little bits of native code in my C# apps, which I tend to do via C++/CLI. Usually I just need to use a C++ library for which there exists no good alternative for .NET; but sometimes performance is a factor too. This is problematic; doing so means adding a reference to a specific x86 or x64 libr...
The main question you should ask yourself is, do you need a 64-bit version. For details see blogs posts by Scott Hanselman and myself. If you really need both versions, you can also load both the 32bit and 64bit library into the GAC, so the runtime can chose the correct one automatically. If you don't want to GAC your...
597,182
597,246
Windows GUI C++ Programming
I want to learn C++ GUI programming using Visual Studio 2008. I'm not sure where to start though. I learned C++ in high school, but not GUI. I've been doing C# for about 3 years now and thats how I "learned" GUI programming. Now I want to learn how to write GUI's without the use of the .NET framework, so where do I sta...
MFC is almost outdated now. I would recommend to use WTL instead . Well it is also not a good idea just to start programming for GUI in C++ when there are so many good frameworks available like QT cross platform framework.
597,217
599,121
Trying to include iPhone OpenGLES headers in C++ code
I have some C++ doing OpenGL drawing and am trying to figure out how to include the opengl headers without it giving me thousands of errors in the obj-c code.
I'm not getting any errors. Are you doing #include <OpenGLES/ES1/gl.h> ?
597,260
597,330
How to determine a windows executables DLL dependencies programmatically?
How to determine what DLL's a binary depends on using programmatic methods? To be clear, I am not trying to determine the DLL dependencies of the running exec, but of any arbitrary exec (that may be missing a required DLL). I'm looking for a solution to implement in a C/C++ application. This is something that needs...
Take a look at the IMAGE_LOAD_FUNCTION API. It will return a pointer to a LOADED_IMAGE structure, which you can use to access the various sections of a PE file. You can find some articles that describe how the structures are laid out here, and here. You can download the source code for the articles here. I think this ...
597,292
597,299
Where exactly do function pointers point?
Given that all the primitive data types and objects have memory allocated, it is intuitively easy to imagine the pointers to these types. But where exactly do function pointers point to? Given that instructions are converted into machine code and reside in memory, should we consider they point to the memory location co...
Function pointer also point into memory, the only difference is that there is executable code at that memory location instead of data. On many platforms if you try to execute data (e.g. regular memory) you'll crash or cause an exception. This is known as Data Execution Prevention - a security measure to prevent applica...
597,311
597,316
Why does the child process here not print anything?
Assume all the variables have been declared previously... because they have been. The child process does not print anything which makes me think it's not being executed. The parent process runs fine, albeit it doesn't get the shared memory. I apologize for the length of this code... // create 5 child process for(int k...
The C stdout stream internally buffers data. It's likely that your "this is child" message is being buffered, and the buffer isn't being flushed by execlp, so it just disappears. Try a fflush(stdout); after the printf. Incidentally, you should do this before the fork() as well, so that child and parent don't both try t...
597,436
597,709
void* as unknown variable type
I'm currently working on a sprite engine in C++. I have an abstract class IEngine with a virtual function init_api. This takes in a void*. // Initialise the engines' API // api_params - void* to api parameters for initalisation // hWnd - window handle virtual bool init_api( void* api_params, HWND hWnd ) = 0; I...
Another way to do it is just have a common header and different *.cpp files for each implementation. That way you can include just the D3D or just the OGL files in your project. IMO its better to choose the API at compile time so your not linking against both libraries. As for the void*, I don't really like it. I ...
597,532
597,550
How do you structure your comparison functions?
I frequently encounter situations, especially with sorting in C++, where I am comparing a series of fields in order to compare a larger structure. A simplified example: struct Car{ Manufacturer make; ModelName model; Year year; }; bool carLessThanComparator( const Car & car1, const Car & car2 ){ if( c...
Well, if your function hits a return in the if clause, there's no need for an explicit else, since it would have already bailed out. That can save on the "indent valley": bool carLessThanComparator( const Car & car1, const Car & car2 ) { if( car1.make < car2.make ) return true; if ( car1.make != car2.m...
597,813
597,820
How to print subscripts/superscripts on a CLI?
I'm writing a piece of code which deals with math variables and indices, and I'd need to print subscripts and superscripts on a CLI, is there a (possibly cross-platform) way to do that? I'm working in vanilla C++. Note: I'd like this to be cross-platform, but since from the first answers this doesn't seem to be possibl...
Since most CLIs are really only terminals (pretty dumb ones mostly but sometimes with color), the only cross-platform way I've ever done this is by allocating muliple physical lines per virtual line, such as: 2 f(x) = x + log x 2 It's not ideal but it's probably the best you're going to get wit...
597,857
597,859
Is friendship inherited in C++?
Suppose I have a Base class: class Base { friend SomeOtherClass; }; And there is another (different) class that inherits from Base: class AnotherClass : public Base {} Is friendship inherited as well?
In principle, a derived class inherits every member of a base class except: * its constructor and its destructor * its operator=() members * its friends So, no. Friends are not inherited.
598,036
598,038
How do I implement operator[] for dynamic array?
I need to implement a dynamic array by myself to use it in a simple memory manager. struct Block { int* offset; bool used; int size; Block(int* off=NULL, bool isUsed=false, int sz=0): offset(off), used(isUsed), size(sz) {} Block(const Block& b): offset(b.offset), used(b.used), size(b.size) {}...
first is a Block pointer so you only need to pass in index. Block* first; ... first[0] //returns the first element first[1] //returns the second element In your example you are passing in too high of an index value when indexing first because you're using sizeof inside. Corrected code: Block& BlockList::operator[](in...
598,143
606,900
Explain about linkages(external/internal) in c++?
Explain about linkages(external/internal) in c++? How does linkage differ for a function,constant,inline function,template function ,class and template class
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=41 check section 3.5 in standard http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf
598,148
598,150
Is it legal to use the increment operator in a C++ function call?
There's been some debate going on in this question about whether the following code is legal C++: std::list<item*>::iterator i = items.begin(); while (i != items.end()) { bool isActive = (*i)->update(); if (!isActive) { items.erase(i++); // *** Is this undefined behavior? *** } else { ...
Quoth the C++ standard 1.9.16: When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement...
598,175
598,176
How do I call a object's member function as a unary_function for std algorithms?
I have a class that looks like this. class A { public: void doSomething(); } I have an array of these classes. I want to call doSomething() on each item in the array. What's the easiest way to do this using the algorithms header?
Use std::mem_fun_ref to wrap the member function as a unary function. #include <algoritm> #include <functional> std::vector<A> the_vector; ... std::for_each(the_vector.begin(), the_vector.end(), std::mem_fun_ref(&A::doSomething)); You can also use std::mem_fun if your vector contains pointers to the c...
598,471
598,808
Weird vertexshader/pixelshader glitch
i've got a little problem with my water effect as you can see here, it doesn't show up the right way. another screen with a diffrent texture applied shows the error in the transform something more clearly my HLSL code: V2P vs(float4 inPos : POSITION, float2 inTex: TEXCOORD) { V2P Output = (V2P)0; float4x4 ...
I guess i found it, the matrix i used for the reflected view, is wrong. When i use the standard view, it works fine
598,552
598,555
Should I learn C before learning C++?
I visited a university CS department open day today and in the labs tour we sat down to play with a couple of final-year projects from undergraduate students. One was particularly good - a sort of FPS asteroids game. I decided to take a peek in the src directory to find it was done in C++ (most of the other projects we...
There is no need to learn C before learning C++. They are different languages. It is a common misconception that C++ is in some way dependent on C and not a fully specified language on its own. Just because C++ shares a lot of the same syntax and a lot of the same semantics, does not mean you need to learn C first....
598,584
599,053
Memory modifying in C++
im trying to learn to modify games in C++ not the game just the memory its using to get ammo whatnot so can someone point me to books
The most convenient way to manipulate a remote process' memory is to create a thread within the context of that program. This is usually accomplished by forcibly injecting a dll into the target process. Once you have code executing inside the target application you are free to use standard memory routines. e.g (memcpy,...
598,913
599,050
Most important things about C++ templates… lesson learned
What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...common mistakes/oversight/assumptions I am starting to implement most of my library/API using templates and would like to collect most common patterns, tips, etc., found in practice. Let me ...
From "Exceptional C++ style", Item 7: function overload resolution happens before templates specialization. Do not mix overloaded function and specializations of template functions, or you are in for a nasty surprise at which function actually gets called. template<class T> void f(T t) { ... } // (a) template<class T...
598,939
598,989
Why do I get E_NOINTERFACE when creating an object that supports that interface?
Note: Using CoGetClassObject, to create multiple objects through a class object for which there is a CLSID in the system registry Single threaded apartment For instance: hresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); IClassFactory *pIClassFactory; hresult = CoGetClassObject (clsid, CLSCTX_LOCAL_SERVER, N...
The problem here is that you are confusing the class object and the object itself. CoGetClassObject will give you a pointer to an object that implements IClassFactory and intended to create an instance of the object you are interested in. It is not an actual instance of that object. In your example, you are getting an ...
598,948
598,970
Creating a project, from Makefile to static/dynamic libraries in UNIX
Guys, would you describe a few things about c++ building blocks, on unix. I want to create an application that links against static libs and dynamic libs (.so). Question 1: How do I create static library using gcc/g++ ?How do I make my app link against it. Question 2: How to specify it in the makefile, linking again...
Static libraries are usually archived with the ar command. Once you build all of the object files (preferably with the -fPIC switch on GCC), you can run ar like so: ar -rs archivename.a list.o of.o objects.o The man page describes the options. Dynamic libraries are built usually with the -shared switch to gcc or ld an...
599,120
599,691
How do you translate this code from Processing to C++?
I wrote this code in Processing (www.processing.org) and was wondering how would one implement it using C++? int i = 0; void setup() { size(1000,1000); } void draw() { // frameRate(120); PImage slice = get(); set(0,20,slice); if( i % 2 == 0 ) fill(128); else fill(0); i++; rect(0,0,width,20); } As you ...
You could also take a look at OpenFrameworks but I doubt that any C++ library will give you such a short implementation.
599,264
599,274
Is there a way to split one texture into an array of them using SOIL in C++?
I'm using SOIL in my project, and I need to take in a single texture, and than convert it into an array of textures using different parts of the first texture. (To use a sprite sheet). I'm using SDL and OpenGL by the way.
The typical way to use sprite sheeting with a modern 3D api like OpenGL is to use texture coordinates to address different parts of your individual texture. While you can split it up it is much more resource friendly to use texture coordinates. For example, if you had a simple sprite sheet with 3 frames horizontally, ...
599,308
599,327
Proper stack and heap usage in C++?
I've been programming for a while but It's been mostly Java and C#. I've never actually had to manage memory on my own. I recently began programming in C++ and I'm a little confused as to when I should store things on the stack and when to store them on the heap. My understanding is that variables which are accessed ve...
No, the difference between stack and heap isn't performance. It's lifespan: any local variable inside a function (anything you do not malloc() or new) lives on the stack. It goes away when you return from the function. If you want something to live longer than the function that declared it, you must allocate it on the ...
599,321
599,353
How to get system time in C++?
In fact i am trying to calculate the time a function takes to complete in my program. So i am using the logic to get system time when i call the function and time when the function returns a value then by subtracting the values i get time it took to complete. So if anyone can tell me some better approach or just how to...
Your question is totally dependant on WHICH system you are using. Each system has its own functions for getting the current time. For finding out how long the system has been running, you'd want to access one of the "high resolution performance counters". If you don't use a performance counter, you are usually limited ...
599,335
599,403
Linker errors with private members of class in header file
I'm trying to build a project in Visual Studio 2008. I'm getting a bunch of linker errors that are really bothering me. My application is a Win32 console application using only native ANSI C++. They are all linker errors of the same pattern. Linker errors are related to every single private static data member of classe...
Maybe you haven't added the library and include paths of the library you use to the project definitions? C++ error are always fun to look at. Or not. In any case, do you initialize your static variables anywhere? You need to do this in a .cpp file somewhere. And remember to use static variables with care. They are act...
599,640
599,649
static member variable of a subclassed class
Is it OK to have a static member variable defined in a base class, and having several derived classes each using its own instance of this member variable? The following code compiles successfully, and prints the right output, but I am still not sure that doing something like that is a good practice. In the following ex...
A very odd use of inheritance indeed. The base class is supposed to define interfaces ideally and contain as little or no state at all if possible according to good OO design principle. This works because your foo() resets the value of A::s everytime it is called. Try printing the address of A::s. There is one and onl...
599,664
599,723
Statically initializing a structure with arrays of varying length
I've got a static map of identifier<=>struct pairs, and each struct should contain some arrays. Everything is known at compile time. That is, I want to have something like this here: ID1 => name: someString flagCount: 3 flags: [1, 5, 10] statically created (if possible). Of course, a declaration like: st...
The elements in an array must be the same size as each other, otherwise you can't use infos[i] to access them - the compiler would have to step through the array and look at the size of each element up to i to find where the next one started. You can allocate enough memory for each element contiguously, and then create...
599,744
599,748
What does the three dots in the parameter list of a function mean?
I came across a function definition like: char* abc(char *f, ...) { } What do the three dots mean?
These type of functions are called variadic functions (Wikipedia link). They use ellipses (i.e., three dots) to indicate that there is a variable number of arguments that the function can process. One place you've probably used such functions (perhaps without realising) is with the various printf functions, for example...
599,769
600,094
How to find what objects a given CLSID supports
Question: Based on a CLSID, how can I find out what objects (or interfaces) it supports for IClassFactory::CreateInstance Note: Currently using CLSIDFromProgID to obtain CLSID
You could use OleView. But if you want to do this programatically then you could use the method that OleView uses. OleView achieves this by just iterating through all the interfaces declared in HKEY_CLASSES_ROOT\Interface and then calling QueryInterface for each of them.
599,996
600,010
C++ FILE readInt function? (from a binary file)
Is there a function for FILE (fopen?) that allows me to just read one int from a binary file? So far I'm trying this, but I'm getting some kind of error I can't see cause the program just crashes without telling me. void opentest() { FILE *fp = fopen("dqmapt.mp", "r"); int i = 0; int j = 0; int k = 0; ...
Now that you have changed your question, let me ask one. What is the format of the file you are trying to read? For a binary file there are some changes required how you open the file: /* C way */ FILE *fp = fopen("text.bin", "rb"); /* note the b; this is a compound mode */ /* C++ way */ std::ifstream ifs("test.txt",...
600,175
600,265
C++ "smart" predicate for stl algorithm
I need to designe predicate for stl algorithms such as find_if, count_if. namespace lib { struct Finder { Finder( const std::string& name ): name_( name ) { } template< typename TElement > bool operator( const TElement& element ) { return ...
Why use template mathods at all? Just use the specific class that you want to base it on or a common base classes if there are lots of class types. e.g. struct Finder { Finder( const std::string& name ): name_( name ) { } bool operator( const IsPresentBaseClass& element ) { return...
600,228
600,632
Creating/Opening Events in C++ and checking if they are fired
I have two threads that use an event for synchronization. In each thread they use the same call: ::CreateEvent( NULL,TRUE,FALSE,tcEventName ) The producer thread is the one that makes the call first, while the consumer thread makes the call last, so it's technically opening, not creating the event... I assume. But, wh...
According to the MSDN documentation for CreateEvent, If the function succeeds, the return value is a handle to the event object. If the named event object existed before the function call, the function returns a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS. Based on your description, I ...
600,400
600,541
Database Structure & Hard drive seek time confusion
could some one help me out trying to understand how hard drive seeking works. I have a small binary database file which read performance is absolutely essential. If I need to skip a few bytes in the file is it quicker to use seek() or to read() then discard the unwanted data. If the average seek time of a hard drive is...
All seek system call does is changing a position in file where the next read will be. It does not move the drive head. Drive heads move when data is read or written and you don't have direct control over what OS will do next. Reading lots of data you aren't going to need has impact because all read data needs space in ...
600,502
600,510
Will the C/C++ compiler optimize this if statement?
I have code like this, and I find it a bit hard to read: // code1 if( (expensiveOperation1() && otherOperation() && foo()) || (expensiveOperation2() && bar() && baz()) { // do something } I just changed it to the following, to make it more readable: // code2 const bool expr1 = expensiveOperation1() && otherOpe...
I would say it shouldn't, since they're not logically equivalent if any of the functions have side-effects. The following would be equivalent however, and it'd have the advantage allowing you to give descriptive names to the test functions, making the code more self-documenting: // code3 inline bool combinedOp1() { ...
600,519
600,560
vector resizing - portable way to detect
I have a vector that I am loading with a know amount of elements (N). The processing dynamically creates new elements, which are appended to the vector. I am expecting about 2 * N additional elements to be created, so I resize the vector to 3 * N. If the additional elements exceed that, I would like a program abo...
Detect what? Whether the vector will be resized? Whether it has been? The only real way to achieve this is to provide checking functionality either in a custom allocator or a function that adds elements to the vector. e.g template<class T> void add_element(std::vector<T>& container, T const& v) { if (container.capac...
600,912
600,927
Pointer mysteriously resetting to NULL
I'm working on a game and I'm currently working on the part that handles input. Three classes are involved here, there's the ProjectInstance class which starts the level and stuff, there's a GameController which will handle the input, and a PlayerEntity which will be influenced by the controls as determined by the Game...
Are you debugging a Release or Debug configuration? In release build configuration, what you see in the debugger isn't always true. Optimisations are made, and this can make the watch window show quirky values like you are seeing. Are you actually seeing the ASSERT triggering? ASSERTs are normally compiled out of Re...
601,152
601,170
Is a finally block without a catch block a java anti-pattern?
I just had a pretty painful troubleshooting experience in troubleshooting some code that looked like this: try { doSomeStuff() doMore() } finally { doSomeOtherStuff() } The problem was difficult to troubleshoot because doSomeStuff() threw an exception, which in turn caused doSomeOtherStuff() to also throw an ...
In general, no, this is not an anti-pattern. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. The whole point of exception handling is that, if you can't deal with it, you let it bubble up to someone who can, through the relatively clean out-of-band signaling ex...
601,180
601,212
why does printf show a 0 for vector size when cout shows the correct size?
I don't get why I get 0 when I use printf and %d to get the size of my vector: vector<long long> sieve; int size; ... //add stuff to vector ... size = sieve.size(); printf("printf sieve size: %d \n", size); //prints "printf sieve size: 0" std::cout << "cout sieve size: "; std::cout << size; std::cout << " \n "; //print...
Now, with the complete source, it is clear. You declared: int size; Then you used: std::printf("current last: %d sieve size: %ld\n", answer, size); std::printf("Limit: %d Answer: %d sieve size: %ld\n", limit, answer, size); If size is int, you should use "%d", not "%ld". A good compiler would have warned you about th...
601,219
601,283
Overloading operator << - C++
Background I have a container class which uses vector<std::string> internally. I have provided a method AddChar(std::string) to this wrapper class which does a push_back() to the internal vector. In my code, I have to add multiple items to the container some time. For that I have to use container.AddChar("First"); con...
Is operator overload written correctly? It is, but one can do better. Like someone else mentioned, your function can be defined entirely out of existing, public functions. Why not make it use only those? Right now, it is a friend, which means it belongs to the implementation details. The same is true if you put opera...
601,268
601,285
visual c++: #include files from other projects in the same solution
I am working on a game using Visual C++. I have some components in separate projects, and have set the project dependencies. How do I #include a header file from a different project? I have no idea how to use classes from one project in another.
Settings for compiler In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration. To access the project configuration: Right-click on the project, and select Properties. Se...
601,337
601,386
Change boost thread priority in Windows
Im trying to change the thread priority in boost but im having no luck. Im getting a bad handle error (type 6) from the GetLastError function. I though native_handle() returned the handle for the thread? Any one know how to do this? void baseThread::applyPriority(uint8 priority) { #ifdef WIN32 if (!m_pThread) ...
Use SetThreadPriority function to set the thread priority. SetPriorityClass is used to set the priority of the process. You also have to change the priority values, see documentation for SetThreadPriority for details.
601,430
601,536
Multibyte character constants and bitmap file header type constants
I have some existing code that I've used to write out an image to a bitmap file. One of the lines of code looks like this: bfh.bfType='MB'; I think I probably copied that from somewhere. One of the other devs says to me "that doesn't look right, isn't it supposed to be 'BM'?" Anyway it does seem to work ok, but on cod...
All three are (probably) equivalent, but for different reasons. bfh.bfType=0x4D42; This is the simplest to understand, it just loads bfType with a number that happens to represent ASCII 'M' in bits 8-15 and ASCII 'B' in bits 0-7. If you write this to a stream in little-endian format, then the stream will contain 'B...
601,558
602,001
Multithreading reference?
I am asking about a good reference for multithreading programming in terms of concepts with good examples using C++/C#?
Good reference for reading: Thread Management In The CLR Round-Robin Access To The ThreadPool Multithreading with C# Why are thread safe collections so hard? Threading in C# Jeffrey Richter’s Power Threading Library Implementing a Thread-Safe Queue using Condition Variables Threading Building Blocks.org! Sutter’s Mill ...
601,676
601,688
Where is Visual C++ Redistributable Installer in VS 2008?
I have Visual Studio 2008 SP1 Professional installed. I have built a C++ application and I want to install the redistributable runtime on another machine. Is the installer available in VS installation? Or do I have to download it?
Take a look in %ProgramFiles%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\ for the platform(s) you require.
601,680
601,685
"Bus error" accessing a set<int> from a struct
Searched for a while, but I can't figure out why this would raise a bus error. Any help would be much appreciated. typedef struct { set<int> pages; } someStruct; ... void someFunction() { ... someStruct *a = createSomeStruct(); // just mallocs and returns a->pages.insert(5); ... }
malloc doesn't initialize the memory it allocates. try with new.
601,763
601,828
How to get IP address of boost::asio::ip::tcp::socket?
I'm writing a server in C++ using Boost ASIO library. I'd like to get the string representation of client IP to be shown in my server's logs. Does anyone know how to do it?
The socket has a function that will retrieve the remote endpoint. I'd give this (long-ish) chain of commands a go, they should retrieve the string representation of the remote end IP address: asio::ip::tcp::socket socket(io_service); // Do all your accepting and other stuff here. asio::ip::tcp::endpoint remote_ep = so...
601,777
613,946
How to configure Eclipse with CDT?
I've been trying to use CDT with Eclipse 3.4 under Windows XP with cygwin. What do I need to do, in order to get startet? I used "eclipse-cpp-ganymede-SR1-win32.zip" found on the Eclipse homepage. Edit: The main problem is, that I cannot compile and run the code. In the run configuration, I tried gcc.exe for the C/C++ ...
I finally found. Thanks guys. After downloading and unpacking "eclipse-cpp-ganymede-SR1-win32.zip", you need to install either Cygwin or MinGW. Make sure the compiler (e.g. gcc.exe) and make.exe is on your $Path. Start Eclipse and everything should work fine.