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
848,144
848,268
How to hide the exporting functions in DLL
I don't want user to see all the exporting functions through Dependence in my DLL, is there a way to do it? I complie my DLL with C++ and MS Visual Studio.
Use a *.def file and use the NONAME attribute to prevent the name's being exported: see Exporting Functions from a DLL by Ordinal Rather Than by Name ... there's an an example here.
848,360
848,384
application couldn't be initialized error (manifest file problem)
I am trying to use a library (.dll) in my project. Everything seems to be set up fine. It all works in release mode. When I go debug on it, I get this darn error on startup: ldr: ... application couldn't be initialized error (or similar, I translated it) I learned that this has to do with manifest files. I fumbled ar...
I always use Dependency Walker for debugging this sort of thing. It will tell you which dependencies your dll is missing.
848,551
848,582
String->Structure CMap
My requirement is that given a string as key to the map, I should be able to retrieve a structure. Can anyone please post sample code for this? Ex: struct { int a; int b; int c; }struct_sample; string1 -> strcut_sample
CMap<CString,LPCTSTR, struct_sample,struct_sample> myMap; struct_sample aTest; aTest.a = 1; aTest.b = 2; aTest.c = 3; myMap.SetAt("test",aTest); ... struct_sample aLookupTest; BOOL bExists = myMap.Lookup("test",aLookupTest); //Retrieves the //struct_sample corresponding to "test"...
849,042
849,303
Implementing "app.exe -instruction file" notation in C++
I have a project for my Data Structures class, which is a file compressor that works using Binary Trees and other stuff. We are required to "zip" and "unzip" any given file by using the following instructions in the command line: For compressing: compressor.exe -zip file.whatever For uncompressing: compressor.exe -...
Lo logré, I gotz it!! I now have a basic understanding on how to use the argc and argv[ ] parameters on the main() function (I always wondered what they were good for...). For example, if I put in the command line: compressor.exe -unzip file.zip Then: argc initializes in '3' (number of arguments in line) argv[0] == "c...
849,168
849,190
Are std::vector elements guaranteed to be contiguous?
My question is simple: are std::vector elements guaranteed to be contiguous? In other words, can I use the pointer to the first element of a std::vector as a C-array? If my memory serves me well, the C++ standard did not make such guarantee. However, the std::vector requirements were such that it was virtually imposs...
This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement. From n2798 (draft of C++0x): 23.2.6 Class template vector [vector] 1 A vector is a sequence container that supports random access iterators. In addition, it supports ...
849,238
854,480
How can I resolve "error LNK2019: unresolved external symbol"?
I've got this MFC application I'm working on that needs to have an embedded database. So I went hunting for a slick, fast "embeddable" database for it and stumbled accross SQLite. I created a DB with it, and I created a static library project with Visual Studio 2008. the library project will be used in another main pro...
It happened to me more than once that I thought symbol XXX (i.e. ?close@CppSQLite3DB@@QAEXXZ) was in the import lib, while the actual symbol was __impXXX (i.e. __imp?close@CppSQLite3DB@@QAEXXZ). The reason for the linker error is then to be found in the compilation step: the compiler will generate the ?close@CppSQLite3...
849,309
849,322
Passing ofstream object from main program to a class
Here is what I am trying to do: 1) Open an ofstream object in my main body. I can do this no problem. 2) Associate this object with a filename. No problem. 3) Pass this object to a class and send output within this class. I can't do this. Here is my code. I would appreciate any help. Thanks! #include <fstream> #in...
You must pass stream objects by reference: Object::Object( ofstream & filein ) { filein << "Success"; } And why are you using a typedef on the class? It should look like this: class Object { public: Object(ofstream & filein); };
849,375
849,398
Determine network interface bandwidth/type without transferring data
Is there any way in Win32 to programmatically determine the bandwidth of a given network interface without actually transferring any data? I only want to distinguish between different types of interface (e.g. dialup vs DSL vs LAN), so a rough order of magnitude is fine, I don't need to actually measure the bandwidth. ...
You can use InternetGetConnectedState to determine the type of connection (LAN/Modem/etc). This will tell you if they have a somewhat decent (non-modem) connection without bandwidth transfer. Unfortunately, you can't really go much beyond that without connecting and transferring data. There is no way for the system t...
849,483
849,504
How do you add conditional breaking based on another breakpoint being hit? Visual C++
I have a bunch of generic code that is used a lot, which i'd like to poke into in order to deal with a bug in a certain specific case. So I'd like to break on a set of breakpoints only if some other breakpoint has been hit. Is there a way to do this in Visual 2005? I'm using C++ code. Thanks!
If the trigger logic is complex enough, sometimes I find it easier to just add a DebugBreak(); call into the source.
849,656
850,251
Launch a URL in a NEW window using C++ (Windows)
How can I launch a URL in a NEW window using C++ (Windows only)? The straight-forward approach seems to open a new tab in an existing browser window. (Or, if tabbed browsing is disabled, the new URL hijacks the existing browser window). This is for a (large) desktop app, using MFC and Qt.
I've used this for showing locally generated html in the default browser, in my case filename is something like "c:\temp\page.html", perhaps replacing filename with the URL might work?? ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); Updated: http://support.microsoft.com/kb/224816 How ShellExecute Determin...
849,711
849,765
TextBox let '\n' be the carriage return
TextBoxes created by "CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", ES_MULTILINE.." require \r\n for a new line. im redirecting my stdoutput into that textbox, which uses just '\n' to indicate a new line. and im not willing to replace all '\n' with '\r\n' isn't there a way to let '\n' beeing a newline in textboxes? thx
I'm pretty sure what you're asking is impossible (i.e. there's no magic setting to make Windows edit controls accept Unix-style newlines).
849,728
863,319
Determining the network connection link speed
How do I programmatically determine the network connection link speed for an active network connection - like Task Manager shows you in the Networking tab? I'm not really after the bandwidth available, just a figure for the current connection, e.g. 54Mbps, 100Mbps etc.
In the end I found the Win32_PerfRawData_Tcpip_NetworkInterface WMI class, as I need to support legacy platforms which, unfortunately, the Win32_NetworkAdapter doesn't do. Win32_PerfRawData_Tcpip_NetworkInterface has a CurrentBandwidth property which gives me what I need on all required platforms (I realise I said I di...
849,812
849,839
C++ - construction of an object inside a class
I'm fairly new to C++, and I'm not sure about this one. Have a look at the following example which sums up my current problem. class Foo { //stuff }; class Bar { Foo foo; }; So Bar constains a full Foo object, not just a reference or pointer. Is this object initialized by its default constructor ? Do I need t...
It will be initialized by its default constructor. If you want to use a different constructor, you might have something like this: class Foo { public: Foo(int val) { } //stuff }; class Bar { public: Bar() : foo(2) { } Foo foo; };
850,062
7,366,855
Debugging C# to Intel C++ in different projects
Similar to this problem here: Old Question about C# debugging I'm trying to debug a library that's used in multiple projects and is compiled using Intel's C++ v 11 compiler (ie, not the standard compiler) in Visual Studio 2008. The current platform I'm using to debug is a C# program that calls the C++ method through a...
The answer: Set the debugging executable and running directory for the dll, and then try to debug from the dll as a separate project. That is, load the intel project in one sln file, and then have the C# project in a different sln file. Then, when you try to debug the dll via f5/the debug button, the executable will s...
850,142
850,150
Need help creating an array of objects
I am trying to create an array of class objects taking an integer argument. I cannot see what is wrong with this simple little code. Could someone help? #include <fstream> #include <iostream> using namespace std; typedef class Object { int var; public: Object(const int& varin) : var(varin) {} } Object; int main (...
In C++ you don't need typedefs for classes and structs. So: class Object { int var; public: Object(const int& varin) : var(varin) {} }; Also, descriptive names are always preferrable, Object is much abused. int main (int argc, char * const argv[]) { int var = 1; Object obj_array[10]; // would work if Object has a...
850,436
850,469
Problem passing a list of objects to another class, C++
Below I have written a sample program that I have written to learn about passing a list of objects to another class. I talk about the problems I am having below. #include <iostream> #include <vector> using namespace std; class Integer_Class { int var; public: Integer_Class(const int& varin) : var(varin) {} int get...
You don't mention what sort of errors you are getting, but one very obvious problem with your code is that the constructor for Contains_List expects a pointer to Integer_Class while the parameter you are sending it (list) is of type vector<Integer_Class>. A vector is not the same as an array, so you cannot pass it as p...
850,575
850,745
start service with out invoking uac
I have noticed some applications (like steam) are able to start/stop services as a normal user with out invoking the uac control. Does any one know how to do it? OS: Vista/Win 7 Visual Studio 2005 C++ . Edit: I was playing around with the steam service last night trying to work out how it is different. If i put my serv...
The ability to start (or stop) a service is controlled by the ACL on the service. If you grant interactive users the right to start your service, they can start your service. It's all in how you set your service up when you installed it. Obviously you'll have to use the Windows service APIs (OpenSCManager/OpenService/...
850,617
850,640
How to extract debugging information from a crash
If my C++ app crashes on Windows I want to send useful debugging information to our server. On Linux I would use the GNU backtrace() function - is there an equivalent for Windows? Is there a way to extract useful debugging information after a program has crashed? Or only from within the process? (Advice along the line...
The function Stackwalk64 can be used to snap a stack trace on Windows. If you intend to use this function, you should be sure to compile your code with FPO disabled - without symbols, StackWalk64 won't be able to properly walk FPO'd frames. You can get some code running in process at the time of the crash via a top-lev...
850,626
850,627
c++ char array out of scope or not?
I have a method that requires a const char pointer as input (not null terminated). This is a requirement of a library (TinyXML) I'm using in my project. I get the input for this method from a string.c_str() method call. Does this char pointer need to be deleted? The string goes out of scope immediately after the call...
The char array returned by string.c_str() is null terminated. If tinyXML's function takes a not null terminated char* buffer, then your probably gonna get some unexpected behaviour. const char* c_str ( ) const; Get C string equivalent Generates a null-terminated sequence of characters (c-string) with the same cont...
850,724
850,728
Why doesn't my change to clog stick?
I think I'm failing to understand some finer point of C++. I want to set up a log of what my program does, and discovered std::clog, which seems to do what I want in theory, but in practice it doesn't. If I do the following, clog works as expected and writes "Test 1" to the screen, and "Test 2" shows up in a file: int ...
I assume you want to create a stack variable of IerrLog. You need to change IerrLog someLog (); to IerrLog someLog; Your original statement will be interpreted by the compiler as a declaration of function someLog() which takes no arguments and returns an IerrLog. You should also create your file as a member variable ...
850,796
850,850
What is the point of pointers?
What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?
Pointers are best understood by C & C++'s differences in variable passing to functions. Yes, you can pass either an entire variable or just a pointer to it (jargon is by value or reference, respectively). But what if the variable is 20 meg array of bytes, like you decided to read an entire file in to one array? Passin...
851,031
853,864
In Qt, how do you properly implement delegates?
I followed the model/view/controller paradigm. I am pretty sure that the model and view are right, but I think I'm doing some things wrong in my delegate. Everything "works", except the first click to a control just "lights up the control" and the second one interacts with it. Is this how delegates are usually imple...
If you are interested in changing the conditions that your custom editor is shown, use QAbstractItemView::setEditTriggers(). Although your delegate is responsible for passing information to and from the custom editor, the view determines when the editor is launched. Documentation reference: http://doc.qt.digia.com/4.5/...
851,041
851,051
How to access a data class's private member variable from another derived class whose parent class is a friend class of the data class?
I have three classes: A data holder class CDataHolder, which uses a Pimpl pattern class CDataHolder { public: // ... private: friend class CBase; struct PImpl; PImpl* iPimpl; }; A base class CBase, which need to access the iPImpl member in CDataHolder, so it is a friend class of CDataHolder class CBase: { prote...
Since you have declared struct PImpl in the private part of CDataHolder class, only friends of CDataHolder can access the same. Why don't you put a forward declaration struct PImpl in the public section or even better before the CDataHolder class?
851,286
855,071
how to use movntdqa to avoid cache pollution?
i am trying to write a memcpy function that does not load the source memory to the cpu cache. The purpose is to avoid cache pollution. The memcpy function below works, but pollutes the cache like the standard memcpy does. i am using P8700 proccesoor with visual C++ 2008 express. i see the cpu cache usage with intel vt...
Quoting from Intel: "The streaming load instruction is intended to accelerate data transfers from the USWC memory type. For other memory types such as cacheable (WB) or Uncacheable (UC), the instruction behaves as a typical 16-byte MOVDQA load instruction. However, future processors may use the streaming...
851,321
851,398
How to check that system is in Log off state?
I want to check that whether the system is in log off state or not in VC++, any ideas?
You can get logon/logoff notifications using various mechanisms (SENS, SCM Notifications if your program is a service, Winlogon notification if you're on XP) You can use WMI to enumerate active sessions. You can use the WTS API to enumerate sessions and query session information.
851,391
851,403
Reading line X until line Y from file in C++
I have a relatively simple question. Say I have a file but I only want to access line X of the file until line Y, whats the easiest way of doing that? I know I can read in the lines one by one keeping count, until I reach the lines that I actually need, but is there a better more elegant solution? Thanks.
In C++, no, not really (well, not in any language I'm familiar with, really). You have to start at the start of the file so you can figure where line X starts (unless it's a fixed-record-length file but that's unlikely for text). Similarly, you have to do that until you find the last line you're interested in. You can ...
851,654
851,808
How can I check is a socket is still open?
I have a C++ app that uses standard socket calls and I want to know if I can tell if a socket is still open without sending or receiving any data. Is there a reliable select or ioctlsocket call I can make?
If you try to recieve one byte, you can receieve several errors, if you were to have a non-blocking socket, and try to receieve on a valid connection, you will get the error WSAEWOULDBLOCK. Knowing this we can check a non blocking socket like so bool connected(SOCKET sock) { char buf; int err = recv(sock, &bu...
851,732
851,823
Problem with boost::bind and member function returning auto_ptr
Why does this code fail to compile with VS 2005: #include <boost/bind.hpp> #include <boost/function.hpp> struct X { typedef std::auto_ptr<int> IntType; // typedef int IntType; // this works IntType memfunc () const { return IntType (); } X () { boost::bind (&X::memfunc, th...
It seems, that, despite the documentation claiming they are equivalent, the following alternative works: boost::bind<IntType> (boost::mem_fn (&X::memfunc), this); Go figure...
852,002
890,430
LLVM what is it and how can i use it to cross platform compilations
I was reading here and there about llvm that can be used to ease the pain of cross platform compilations in c++ , i was trying to read the documents but i didn't understand how can i use it in real life development problems can someone please explain me in simple words how can i use it ?
The key concept of LLVM is a low-level "intermediate" representation (IR) of your program. This IR is at about the level of assembler code, but it contains more information to facilitate optimization. The power of LLVM comes from its ability to defer compilation of this intermediate representation to a specific target ...
852,070
852,109
Multiply defined symbols
If I declare a global variable in a header file and include it in two .cpp files, the linker gives an error saying the symbol is multiply defined. My question is, why does this happen for only certain types of object (eg. int) and not others (eg. enum)? The test code I used is given below: test.h #ifndef TEST_HEADER #d...
That's because enumerations are not objects - they are types. Class types (class,struct,union) and enumerations can be defined multiple times throughout the program, provided all definitions satisfy some restrictions (summed up by the so-called One Definition Rule (ODR)). The two most important ones are All definition...
852,162
852,208
dynamic structures in static memory?
GIVEN that you have a fixed area of memory already allocated that you would like to use, what C or C++ libraries will allow you to store a dynamic structure (e.g. a hash) in that memory? i.e. the hash library must not contain any calls to malloc or new, but must take a parameter that tells it the location and size of t...
You can write your own custom allocators for STL containers. Dr.Dobb's: What Are Allocators Good For? SO: Compelling examples of custom C++ STL allocators?
852,334
854,692
How to interpret binary data in C++?
I am sending and receiving binary data to/from a device in packets (64 byte). The data has a specific format, parts of which vary with different request / response. Now I am designing an interpreter for the received data. Simply reading the data by positions is OK, but doesn't look that cool when I have a dozen differ...
I've done this innumerable times before: it's a very common scenario. There's a number of things which I virtually always do. Don't worry too much about making it the most efficient thing available. If we do wind up spending a lot of time packing and unpacking packets, then we can always change it to be more efficient....
852,377
852,426
How to ask for a small addition? (syntax of pure virtual functions)
In the current C++0x draft I've noticed they introduced some new explicit keywords to highlight expected behaviors (great move!). Examples: defaulted/deleted functions (= default and = delete), the new nullptr constant, the explicit keyword usable also for conversion operators, ... So I expected to see also a = pure sy...
That's not a small pedantic change. Introducing a new keyword is one of the biggest changes you can ask for. It is something they try to avoid almost at any cost. Think of all the code that uses the word "pure", which would break. In general, their guideline is to only add things to the language that could not be done ...
852,568
29,309,756
Version resource in DLL not visible with right-click
I'm trying to do something which is very easy to do in the regular MSVC, but not supported easily in VC++ Express. There is no resource editor in VC++ Express. So I added a file named version.rc into my DLL project. The file has the below content, which is compiled by the resource compiler and added to the final DLL. T...
The correct solution is to add to the top of your .rc file: #include <windows.h>
852,676
852,688
Is "boolean short circuiting" dictated by standard or just mostly used as optimization?
Consider this Class* p = NULL; if( p != NULL && p->Method() == OK ){ // stuff } On all compilers I've worked with, this is quite safe. I.e. the first part of the boolean expression will evaluate to false, and the call to Method() will thus not be attempted since evaluating the second part is redundant. Is this beca...
This is called boolean short circuiting and is defined into many languages. Here is a wikipedia article that describes which languages have this feature. Now that you know the correct name for the feature, there are other SO articles about it as well.
852,752
853,420
How to know when a new USB storage device is connected in Qt?
I want to know when a USB device is connected to the computer that my Qt application is running on (in Windows). In my main QWidget, I've reimplemented winEventFilter like this: bool winEventFilter ( MSG * msg, long * result ) { qDebug() << msg; return false; } I'd expect qDebug to send at least something when...
I believe what you may be missing is the call to register for device notification. Here is code that I use to do the same thing, though I override the winEvent() method of the QWidget class and not the winEventFilter. // Register for device connect notification DEV_BROADCAST_DEVICEINTERFACE devInt; ZeroMemory( &devInt...
852,856
852,893
Win32, C++: Creating a popup window without stealing focus
I am creating a program that displays a popup at certain times (just like some chat clients for example) on which the user can click. However, I do not want to take away the focus from the current application. The way I'm doing it now is by using a HWND with WS_POPUPWINDOW and minimizing and then restoring the window....
To show without activating: ShowWindow(hwnd, SW_SHOWNOACTIVATE); To raise without activating: SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
853,007
853,040
Find the elements of an array based on minimum sum
I've written a loop in C++ to give me 6 random numbers and store them in an array. What I would like to do is to sum the elements of the array until I get a value larger than a number, "x", but I would like to do this without necessarily adding all the elements. The objective is to find the first elements which sum t...
Write a functor that does the addition. #include <algorithm> struct SumToo { SumToo(int val):m_val(val),m_sum(0) {} int m_val; int m_sum; bool operator()(int next) { m_sum += next; return m_sum >= m_val; } }; int main() { int data[] = {1,2,3,4,5,6}; in...
853,304
859,853
Windows volume device detect failed until reboot. Never failed before
I have code to detect the connection of USB Flash Drives as volumes. The code has been working very well for awhile, but recently a fellow engineer's machine started to fail and didn't work right again until it was restarted. The project uses Qt 4.5.0, but that shouldn't be very relevant to this question. I register f...
My guess would be that you would see the DBT_DEVTYP_DEVICEINTERFACE normally anyway. USB devices are self-describing. A USB device can have any "interfaces" where each interface is a feature of the device. My guess is that when a USB is connected you get a "DBT_DEVTYP_DEVICEINTERFACE" per USB device interface so tha...
853,316
853,606
Is Critical Section always faster?
I was debugging a multi-threaded application and found the internal structure of CRITICAL_SECTION. I found data member LockSemaphore of CRITICAL_SECTION an interesting one. It looks like LockSemaphore is an auto-reset event (not a semaphore as the name suggests) and operating system creates this event silently when fi...
When they say that a critical section is "fast", they mean "it's cheap to acquire one when it isn't already locked by another thread". [Note that if it is already locked by another thread, then it doesn't matter nearly so much how fast it is.] The reason why it's fast is because, before going into the kernel, it uses t...
853,368
853,646
Underlying type of a C++ enum in C++0x
I've been trying to read a bit of the C++ standard to figure out how enum's work. There's actually more there than I originally thought. For a scoped enumeration, it's clear that the underlying type is int unless otherwise specified with an enum-base clause (it can be any integral type). enum class color { red, green, ...
I haven't read any C++0x stuff so I couldn't comment on that. As for serializing, you don't need the switch when reading the enum back in - just cast it to the enum type. However, I don't cast when writing to the stream. This is because I often like to write an operator<< for the enum so I can catch bad values being w...
853,559
853,704
What memory management do I need to cleanup when using TinyXml for C++?
I'm doing the following with TinyXml: TiXmlDocument doc; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); TiXmlElement* main = new TiXmlElement("main"); TiXmlElement* header = new TiXmlElement("header"); header->SetAttribute("attribute","somevalue"); main->LinkEndChild(header); // ... Add many more TiX...
The documentation for LinkEndChild says this: NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions.
854,541
854,594
Layout of Pixel-data in Memory?
I'm writing a C++ library for an image format that is based on PNG. One stopping point for me is that I'm unsure as to how I ought to lay out the pixel data in memory; as far as I'm aware, there are two practical approaches: An array of size (width * height); each pixel can be accessed by array[y*width + x]. An array ...
Off the top of my head: The one thing that would make me choose #2 is the fact that your memory requirements are a little relaxed. If you were to go for #1, the system will need to be able to allocate height * width amount of contiguous memory. Whereas, in case of #2, it has the freedom to allocate smaller chunks of c...
854,681
855,246
C++ compiler error in netbeans
I've tried everything from reading the Netbeans help to browsing Google. This code works fine in Dev-Cpp but not Netbeans 6.5.1. Netveans also places and exclamation mark next to #include <iostream> which i checked and is in the include path of netbeans and is in the include folder: #include <iostream> int main() { ...
The cause of the error is that Netbeans is incompatible with MinGW's make. You have a choice of supported make versions: Cygwin's make. Cygwin is a blessing. It brings as much Unix to Windows as you'd like. MinGW's own MSYS, which "is a collection of GNU utilities such as bash, make, gawk and grep to allow building of...
854,864
854,957
When and why is an std::__non_rtti_object exception generated?
I'm using Visual Studio and performing a valid dynamic cast. RTTI is enabled. Edit : Updated the code to be more realistic struct base { virtual base* Clone() { base* ptr = new base; CopyValuesTo( ptr ); return ptr; } virtual void CopyValuesTo( base* ptr ) { ... ...
I ran a test based on your pseudo-code and it works. So if RTTI is truly enabled in your build configuration, then it must be another problem that isn't captured in what you posted.
855,021
855,039
How do I access internal members of a union?
I have a union that is defined like this: typedef union { enum { REVISION = 0, CURRENT_VERSION = REVISION }; enum FLAGS{ FLAG_DEFAULT = 0x00000000, FLAG_EOD = 0x00000001, FLAG_OUTOFORDER = 0x00000002 }; CHAR _filler[32]; struct INTERNAL_STRUC...
You have declared the type called INTERNAL_STRUCTURE, but not an actual instance of that type. Try this: typedef union { //... CHAR _filler[32]; struct { UINT16 type; UINT16 flags; } INTERNAL_STRUCTURE; }CORRHDR; Then to access the field: CORRHDR ch; printf("%u\n", ch.INTERNAL_STRUCTURE.type);
855,110
855,131
Why is the use of tuples in C++ not more common?
Why does nobody seem to use tuples in C++, either the Boost Tuple Library or the standard library for TR1? I have read a lot of C++ code, and very rarely do I see the use of tuples, but I often see lots of places where tuples would solve many problems (usually returning multiple values from functions). Tuples allow you...
Because it's not yet standard. Anything non-standard has a much higher hurdle. Pieces of Boost have become popular because programmers were clamoring for them. (hash_map leaps to mind). But while tuple is handy, it's not such an overwhelming and clear win that people bother with it.
855,121
855,291
C++ Custom Enum Struct for INI file reader
I'm trying to create an Enum that has a string label and a value and I plan to use this to read stuff from an ini file. For example in the ini file I might have some double, int or string type values preceded by the tag/name of the value: SomeFloat = 0.5 SomeInteger = 5 FileName = ../Data/xor.csv When I read the tag f...
If you have limited and very stable set of types, then Boost.Variant may be used. If you going to add support for new types later, then better forget about this method. In this situation solution, based on Boost.Any, or pair of strings will be better. typedef boost::variant<int, double, std::string> ValueType; struct E...
855,123
855,227
Is it possible to make a factory in C++ that complies with the open/closed principle?
In a project I'm working on in C++, I need to create objects for messages as they come in over the wire. I'm currently using the factory method pattern to hide the creation of objects: // very psuedo-codey Message* MessageFactory::CreateMessage(InputStream& stream) { char header = stream.ReadByte(); switch (h...
I think that the open/closed approach and DRY are good principles. But they are not sacred. The goal should be making the code reliable and maintainable. If you have to perform unnatural acts to adhere to O/C or DRY, then you may simply be making your code needlessly more complex with no material benefit. Here is ...
855,417
855,444
Mapping from character id to a class name in c++ via templates?
Duplicate: Is there a way to instantiate objects from a string holding their class name? Is there a (better) way in C++ to map string id to a class name. I suspect there might be a way via templates but I wasn't able to figure out the correct way. For example if I have multiple messages, each storing in the first byt...
As someone else said, it can't be done using templates (templates are computed at compile time. But your character id is compute at runtime). You can use a map from id to constructor function. It boils down to this question: Instantiate objects from a String holding their class name I recommend you to keep it simple. ...
855,996
856,026
C++ Equivalent to Designated Initializers?
Recently I've been working on some embedded devices, where we have some structs and unions that need to be initialized at compile time so that we can keep certain things in flash or ROM that don't need to be modified, and save a little flash or SRAM at a bit of a performance cost. Currently the code compiles as valid ...
I'm not sure you can do it in C++. For the stuff that you need to initialize using designated initializers, you can put those separately in a .c file compiled as C99, e.g.: // In common header file typedef union my_union { int i; float f; } my_union; extern const my_union g_var; // In file compiled as C99 co...
856,200
856,277
C++: First element of vector "corrupting"
I have a class (foo) that contains a vector. If i try iterating over the elements in the vector like so: for(vector<random>::iterator it = foo.getVector().begin(); it != foo.getVector().end(); ++it) { cout << (*it) << endl; } The first element is always corrupted and returns garbage data. However, if do som...
for(vector<random>::iterator it = foo.getVector().begin(); The temporary vector is returned when you do foo.getVector() and it gets destroyed the moment ; is encountered after foo.getVector().begin(); Hence iterator becomes invalid inside the loop. If you store the value of foo.getVector(); in vector v ( v = foo.g...
856,321
856,478
Why is it necessary to add new events to the *end* of an IDL interface?
I have found that when I add new events to an existing COM/IDL interface, I sometimes run into strange issues unless they are added to the end of the interface. For example, say I have the following interface: interface IMyEvents { HRESULT FooCallback( [in] long MyParam1, [in] long MyParam2, ...
You are not supposed to modify an existing COM interface. Clients that were not compiled with the change are not aware of it and will continue calling as they had done before the change. The result is that existing clients call BarCallback with a long integer, but instead get NewCallback that thinks this long integer ...
856,463
856,486
How to remove/delete executable files (aka files without extension) only
I have a directory src/ that contain many .cc files and its binary. For example: src/ |_ foo.cc |_ bar.cc |_ qux.cc |_ thehead.hh |_ foo (executable/binary) |_ bar (executable/binary) |_ qux (executable/binary) |_ makefile In reality there are many .cc and executable files. I need to remove those bi...
you can run find . -perm +100 -type f -delete
856,466
856,517
Very strange visual studio behaviour with excessive lines of whitespace
yesterday we updated to a new version of some middleware we are using, and had a very bizarre merge problem with perforce... it had created approximately 10-20 thousand lines of white space in one of my functions, this all compiled fine, upon running the program it crashed indicating some memory issue, tracing back thr...
Are you sure it's white space and not Whitespace?
856,542
856,839
Elegant solution to duplicate, const and non-const, getters?
Don't you hate it when you have class Foobar { public: Something& getSomething(int index) { // big, non-trivial chunk of code... return something; } const Something& getSomething(int index) const { // big, non-trivial chunk of code... return something; } } We can't impl...
I recall from one of the Effective C++ books that the way to do it is to implement the non-const version by casting away the const from the other function. It's not particularly pretty, but it is safe. Since the member function calling it is non-const, the object itself is non-const, and casting away the const is allow...
856,545
856,594
C++ Library requires LibCurl - will users of the app need libcurl?
I'm normally a Java developer, but I'm writing a C++ library right now they will use LibCurl. And I'm very un-aware in the C++ world! What I'm writing is infact a library for use by other developers (its a client code used to access our API). Will end users be required to have libcurl installed, or can the developers s...
If you link libcurl statically then the end-user does not require libcurl, as it will be linked into to the executable directly at compile time. If you link libcurl dynamically, then the end-user does require libcurl to be installed on their system and available as a shared object library. However, you're in a differen...
856,551
856,587
C++ Converting a Datetime String to Epoch Cleanly
Is there a C/C++/STL/Boost clean method to convert a date time string to epoch time (in seconds)? yyyy:mm:dd hh:mm:ss
See: Date/time conversion: string representation to time_t And: [Boost-users] [date_time] So how come there isn't a to_time_t helper func? So, apparently something like this should work: #include <boost/date_time/posix_time/posix_time.hpp> using namespace boost::posix_time; std::string ts("2002-01-20 23:59:59"); ptime...
856,617
857,505
xcode gives syntax error on cpp code
I am trying to reuse Apple's Speak Here sample code in my own iPhone app. I downloaded and compiled the project with no problems, so I then added some of the files to my own application. When I try to compile my own application, the compiler gives me MeterTable.h:54: error: syntax error before 'MeterTable' The relevan...
You're including "MeterTable.h" in a non C++ file other than MasterTable.mm. The error is not in 'MeterTable.h' but in the header included before it. Note that <stdlib.h>... can be a noop if they are included before. If you want to make sure your file is compiled with C++, you can add this code to the begining of Mas...
856,653
1,222,030
C++ namespace problem with ARM RealViewICE
I'm using ARM RealView debug 3.1 and I'm unable to watch variables inside functions defined in a C++ namespace, the code works well and is compiled with armcc. Do any of you know a solution for this?
Well, arm confirmed this bug.
857,072
857,104
Can I iterate over the elements that are in one range of iterators but not in another?
Let's say I have a sequential container, and a range (pair of iterators) within that container of elements that are currently 'active'. At some point, I calculate a new range of elements that should be active, which may overlap the previous range. I want to then iterate over the elements that were in the old active ran...
You can use two sets for the last active range and another for the current active range. Use the set_difference algorithm to get the objects to be activated/deactivated.
857,085
857,285
What is the most correct way to hide an autocomplete popup?
I'm developing a custom autocomplete control in pure WinApi, and the problem that I've encountered is that I don't know how to hide the popup window when clicked outside of the control (e.g. emulate the combobox dropdown behavior). How is it usually implemented? Should I use mouse capture? Thanks. UPD: Tracking keyboar...
After reading this article I now believe that using SetWindowsHookEx and a WH_MOUSE hook is the way to go. But maybe there is a simpler solution?
857,113
857,132
Calling overridden function from the overriding function
Suppose I have virtual function foo() in class B, and I need slightly different behavior in one of B's derived classes, class D. Is it OK to create an overriding function D::foo(), and call B::foo() from there, after the special case treatment? Like this: void D::foo() { if (/*something*/) // do something else...
This is perfectly good. In fact, the canonical way of performing some operations is calling the base class method, then do whatever (or the other way around). I am thinking of operator= here. Constructors usually work that way, too, even if this is a bit disguised in the initialization list.
857,135
859,447
How to handle messages from dynamically created controls in an MFC app?
Imagine I have a CDialog which creates controls dynamically when the user clicks a button. It could be like this: // We don't know which is the first id for the new buttons until runtime (!) MyDialog::MyDialog(/*whatever parameters needed*/, first_id) : next_id_(first_id) { /*...*/ } BOOL MyDialog::OnSomeButtonClic...
These are the solutions I've found so far in order of relevance: Use ON_COMMAND_RANGE if you can define the range of the control IDs you want to handle. Overload CWnd::PreTranslateMessage() and do whatever stuff you want with the messages received. NOTE: When dealing with buttons, take into account that the BN_CLICKED...
857,258
857,280
c++ constant in library; does not work
anyone knows why this does not work when I try to include a library with the following declarations: namespace wincabase { const char* SOMESTRING = "xx"; } While this is perfectly fine: namespace wincabase { const int X = 30; } I get a "multiple definitions" error with gcc for the first case when I link the lib. ...
const char* means pointer to const char. This means the pointer itself is not constant. Hence it's a normal variable, so you'd need to use extern const char* SOMESTRING; in the header file, and const char* SOMESTRING = "xx"; in one compilation unit of the library. Alternatively, if it's meant to be a const pointer t...
857,347
858,153
Call COM exe API from NSIS script
Is it possible to call an api exposed in COM exe server from NSIS script? I am not able to find any documentation for that. If anyone knows , please reply.
The basic syntax looks like: System::Call "$0->2()" where $0 is the COM object and 2 is the 0 based index of the method in the vtable (2 is Release) http://nsis.sourceforge.net/System_plug-in_readme#Usage_Examples_2
857,395
858,128
Alternatives to preprocessor directives
I am engaged in developing a C++ mobile phone application on the Symbian platforms. One of the requirement is it has to work on all the Symbian phones right from 2nd edition phones to 5th edition phones. Now across editions there are differences in the Symbian SDKs. I have to use preprocessor directives to conditionall...
I've been exactly where you are. One trick is, even if you're going to have conditions in code, don't switch on Symbian versions. It makes it difficult to add support for new versions in future, or to customise for handsets which are unusual in some way. Instead, identify what the actual properties are that you're rely...
857,786
858,022
Call member functions of members of elements of a container with for_each?
Confusing title, hopefully some code will clarify: struct MyNestedType { void func(); }; struct MyType { MyNestedType* nested; } std::vector<MyType> vec; // ... populate vec // I want something approximating this line, but that doesn't use made-up C++! std::for_each(vec.begin(), vec.end(), std::mem_fun_ref(...
You can use such functor template <typename T, T* MyType::* TMember, void (T::* TNestedMember)() > struct Caller { Caller() { } template <typename TObject> void operator()(TObject object) { (object.*TMember->*TNestedMember)(); } }; To solve your problem struct MyNestedType { MyNestedT...
857,962
858,013
Qt QImage pixel manipulation problems
I'm currently in the process of writing a steganography application with Qt. I am trying to hide my message bits in the least significant bit of the blue colour of the pixel. From debugging I can tell that this section is working as it should. However after hiding my bits in the message I then save the image and then r...
Make sure you're not saving using a lossy format, such as JPEG.
858,035
858,057
Union – useless anachronism or useful old school trick?
I recently came across a great data structures book,"Data Structures Using C" (c) 1991, at a local Library book sale for only $2. As the book's title implies, the book covers data structures using the C programming language. I got the book knowing it would be out-dated but would probably contain lots of advanced C topi...
UNIONs implement some sort of polymorphism in a non-OOP world. Usually, you have a part which is common and depending on that part, you use the rest of the UNIONs. Therefore, in such cases where you do not have an OOP language and you want to avoid excessive pointer arithmetic, unions can be more elegant in some cases....
858,252
858,322
Alternatives to MS strncpy_s
What are some alternatives to the Microsoft security enhanced functions such as strncpy_s or _itoa_s? Although developing in MS environment the goal is to write code that could be ported easily to other platforms.
Rageous is correct, there is no complex logic behind it. I would just use Microsoft's version for now and if you decide to port to another OS later, THEN implement it yourself for the target platform and use preprocessor commands to specify your implementation on the non-Windows platform(s).
858,338
858,436
what could be wrong with: char* param= new char[200];
I'm writing a program in C++ and for some reason I'm getting a segmentation error at the following line: char* param= new char[200]; I've tried different variations and even tried putting before it int* param= new int;//for no reason and the same error occurs. What might I have done to cause this problem? What could ...
I'd say Neil's on the right track - it's probably something you trampled earlier on that's only being caught there. Have you made sure that: All previous allocations succeeded. You've not written past the end or beginnings of any arrays (there's a plethora of information and tools for bounds checking out there). [Edi...
858,977
859,086
C enum different compilers
I'm building an application that needs to compile on both Windows and Linux. The application is written in C, almost everything works except the MinGW compiler refuses this typedef struct somestruct{ ...snip... enum {NODE, REAL} type; }; somestruct* something; switch (something->type){ case NODE: ...stuff......
If you get rid of the nesting, it should work portably: typedef enum somestruct_type { somestruct_type_NODE, somestruct_type_REAL } somestruct_type; typedef struct somestruct { ...snip... somestruct_type type; } somestruct; I have seen code very similar to this be ported to a large number of C and C++ compil...
859,267
859,393
Stange seg fault when using += with strings
There must be something obvious I don't realize about C++ with this one. load(string & filename){ string command; char delimiter = '/'; size_t delimiterPos = filename.rfind(delimiter); string directory = string(filename.c_str(),delimiterPos); command = "import path "; //want to add directory to end of command ...
Maybe it has to do with how you are constructing "directory" here size_t delimiterPos = filename.rfind(delimiter); string directory = string(filename.c_str(),delimiterPos); Is rfind somehow failing? If rfind failed, it would return std::npos as specified here. I'm not sure what the behavior would be if you passed np...
859,304
859,841
Convert CString to const char*
How do I convert from CString to const char* in my Unicode MFC application?
To convert a TCHAR CString to ASCII, use the CT2A macro - this will also allow you to convert the string to UTF8 (or any other Windows code page): // Convert using the local code page CString str(_T("Hello, world!")); CT2A ascii(str); TRACE(_T("ASCII: %S\n"), ascii.m_psz); // Convert to UTF8 CString str(_T("Some Unico...
859,433
864,504
Which issues have you encountered due to sequence points in C and C++?
Below are two common issues resulting in undefined behavior due to the sequence point rules: a[i] = i++; //has a read and write between sequence points i = i++; //2 writes between sequence points What are other things you have encountered with respect to sequence points? It is really difficult to find out these issu...
Here is a simple rule from Programming principles and practices using c++ by Bjarne Stroustup "if you change the value of a variable in an expression.Don't read or write twice in the same expression" a[i] = i++; //i's value is changed once but read twice i = i++; //i's value is changed once but written twice
859,501
1,988,688
Learning OpenGL in Ubuntu
I'm trying to learn OpenGL and improve my C++ skills by going through the Nehe guides, but all of the examples are for Windows and I'm currently on Linux. I don't really have any idea how to get things to work under Linux, and the code on the site that has been ported for Linux has way more code in it that's not expla...
The first thing to do is install the OpenGL libraries. I recommend: freeglut3 freeglut3-dev libglew1.5 libglew1.5-dev libglu1-mesa libglu1-mesa-dev libgl1-mesa-glx libgl1-mesa-dev Once you have them installed, link to them when you compile: g++ -lglut -lGL -lGLU -lGLEW example.cpp -o example In example.cpp, include ...
859,517
859,529
OSX equivalent of ShellExecute?
I've got a C++ app that I'm porting from Win32 to OSX. I'd like to be able to launch arbitrary files as if the user opened them. This is easy on windows using ShellExecute. How do I accomplish the same thing on the Mac? Thanks!
You can call system(); in any C++ application. On OSX, you can use the open command to launch things as if they were clicked on. From the documentation for open: The open command opens a file (or a directory or URL), just as if you had double-clicked the file's icon. If no application name is specified, the default ap...
859,535
859,586
How do I convert a big-endian struct to a little endian-struct?
I have a binary file that was created on a unix machine. It's just a bunch of records written one after another. The record is defined something like this: struct RECORD { UINT32 foo; UINT32 bar; CHAR fooword[11]; CHAR barword[11]; UNIT16 baz; } I am trying to figure out how I would read and interpret this ...
As well as the endian, you need to be aware of padding differences between the two platforms. Particularly if you have odd length char arrays and 16 bit values, you may well find different numbers of pad bytes between some elements. Edit: if the structure was written out with no packing, then it should be fairly straig...
859,963
859,974
What does the | operator mean in a function call? [C++]
I usually see this when looking at Win32 gui code. My assumption is that it is a standard bitwise or, but I also occasionaly see it in C#, and it seems like there would be a better (well higher level) way to do the same thing there. Anyway, here's an example: MessageBox(NULL, "Window Creation Failed!", "Error!", MB_I...
The | is a bitwise OR. MB_OK and MB_ICONEXCLAMATION are defined constants which are a power of 2 (such as 32 or 128), so that the bitwise OR can combine them (128 | 32 would be 160, which has two bits set). This is normal when the bits are used as flags.
860,339
860,353
What is the difference between public, private, and protected inheritance in C++?
What is the difference between public, private, and protected inheritance in C++? All of the questions I've found on SO deal with specific cases.
To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:". There are three accessors that I'm aware of: public, protected and private. Let: class Base { public: int publicMember; protected: int protectedMember; ...
860,447
860,452
What is the array form of 'delete'?
When I compiled a code using the array name as a pointer, and I deleted the array name using delete, I got a warning about deleting an array without using the array form (I don't remember the exact wording). The basic code was: int data[5]; delete data; So, what's the array form of delete?
The array form of delete is: delete [] data; Edit: But as others have pointed out, you shouldn't be calling delete for data defined like this: int data[5]; You should only call it when you allocate the memory using new like this: int *data = new int[5];
860,468
860,484
Including */ in a C-style block comment
Is there any way to include */ in a C-style block comment? Changing the block comment to a series of line comments (//) is not an option in this case. Here's an example of the sort of comment causing a problem: /** * perl -pe 's/(?<=.{6}).*//g' : Limit to PID */
Usually comments don't need to be literal, so this doesn't come up too often. You can wrap it all in a #if block: #if 0 whatever you want can go here, comments or not #endif
860,602
860,617
Recommended Open Source Profilers
I'm trying to find open source profilers rather than using one of the commercial profilers which I have to pay $$$ for. When I performed a search on SourceForge, I have come across these four C++ profilers that I thought were quite promising: Shiny: C++ Profiler Low Fat Profiler Luke Stackwalker FreeProfiler I'm not ...
You could try Windows Performance Toolkit. Completely free to use. This blog entry has an example of how to do sample-based profiling.
860,673
879,992
Programmatically disable/enable network interface
I'm trying to come up with a solution to programmatically enable/disable the network card - I've done a ton of research and nothing seems to be a workable solution in both XP and Vista environments. What I'm talking about is if you went into the Control Panel 'Network Connections', right clicked on one and picked eith...
After testing on more platforms and more approaches, I've basically given up on this functionality (at least for my purposes). The problem for me is that I want to have something that works in 90%+ of the situations, and the reality is that with everything I could come up with, it's closer to 70%. The ironic thing is...
860,685
860,788
Reading from file using fgets() causes "Access Violation reading from address..." c++
I'm Using FILE * F opened in _sfopen () I'm reading from the file in while(!feof(f)) and then fgets(str,1024,f) when running reaches the last line it still goes in the while but then when trying to fgets it flies out with an access violation arror (menwhile I just put a try and catch(...) but I know It's not a good so...
You specified C++ as tag, maybe use a filestream (std::ifstream for input from file) and the global getline() function to get it line by line and put it in a std::string for further analysis/manipulation. For an example look here (2nd example in the "Text files" paragraph)
860,779
860,934
Collision problems with OSlib for psp in C++
Im using oslib with the pspsdk toolchain and for some reason this doesnt work the way I think it would float spritewidth = sprite->stretchX; float spriteheight = sprite->stretchY; float bushwidth = bush->stretchX; float bushheight = bush->stretchY; //Basic border collision if (sprite->x <= 0) sprite->x = 0; if (sp...
One thing you can do, is instead of having the character "move backwards" when he hits the bush, you can have his position changed. What I mean is something like this: (Using only up for the example). if (osl_keys->held.up) { if (bushcol == 0) { sprite->y -= 4; sprite_position = UP; SpriteAn...
860,863
860,883
Why does a compiler dislike implicitly casting to uint's?
I have run into a couple of similar quirks regarding uint usage in both C++ and C#, and now I'm wondering on the reasoning (which may be completely different for each example). For both of these examples, note that I am compiling with the warning levels set to maximum. (1) gcc complains about comparing an int to a uin...
I can't speak for gcc but as for the C# 3 compiler you need to explicitly tell it that these ints ought to be unsigned: uint foo = condition ? 1U : 2U; The C# compiler loves ints and assumes all integral values within range are ints. Since your expression is using a conditional operator the compiler is too eager to a...
860,877
860,980
Using typedefs (or #defines) on built in types - any sensible reason?
Well I'm doing some Java - C integration, and throught C library werid type mappings are used (theres more of them;)): #define CHAR char /* 8 bit signed int */ #define SHORT short /* 16 bit signed int */ #define INT int ...
The C standard doesn't specify the size of a number of the integer types; it depends on the compiler, and the processor on which the code will run. Therefore, for maximum portability, it's best to have a header which uses standard names which indicate how big each type is for that particular target. MISRA-C and others ...
860,880
863,093
Why would I get a GPF in DLLMain when run as a restricted user?
Why is this code crashing when run as a restricted user, but not when run as an admin of the machine? extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { hInstance; m_hInstance=hInstance; return _AtlModule.DllMain(dw...
When you get an error saying you can't reference a memory at some 0x0000... location, it usually means your code is trying to reference a member variable of some object, but the object pointer points to NULL. In this case, the member variable is 0x34 bytes into the object. Further guessing, given that it only fails whe...
860,923
863,606
Unit testing with -fno-access-control
I have seen many crazy methods to get access to private variables when unit testing. The most mind-blowing I've seen is #define private public. However, I've never seen anyone suggest turning off private variables at the compiler level. I had always just assumed that you couldn't. I've complained to many a developer...
I would argue that unit tests should not need access to private members. In general, unit tests are meant to test the interface to your classes, not the internal implementation. That way, changes to the internals will only break the tests if the interface has been compromised. Have a look at my answer to a similar ques...
861,007
861,032
How do I bounce a point off of a line?
I'm working on writing a Pong game and I've run across a problem. I'm trying to figure out how to bounce a point off of a line. The best method I can figure out to do this with is Calculate the current and future position of the Ball. Line Segment: {Ball.location, Ball.location + Ball.direction} (Ball.location an...
You just need to check if the center of the ball is within its radius of the paddle to tell whether or not its time to bounce. There was an older question asked that has several answers on calculating bounce angle.
861,133
861,497
Accessing a template base classes function pointer type
I have a class that I've been provided that I really don't want to change, but I do want to extend. I'm a pattern and template newbie experimenting with a Decorator pattern applied to a template class. Template class contains a pointer-to-member (if I understand the semantics correctly) in yet another class. The poi...
The compile error is due to the fact that the compiler can't tell you are talking about a type. Try: D( typename B<T>::MYFUN *fPtr, B<T> *providedBase ); and template <typename T> D<T>::D( typename B<T>::MYFUN *p, B<T> *base ) See: the templates section of the C++ FAQ Lite for more details on why this is necessary, ...
861,154
863,583
Winsock error code 10014
string SendRequestToServer(std::string url) { struct sockaddr_in addr = { 0 }; struct hostent *host = NULL; // If the URL begins with http://, remove it. if(url.find("http://") == 0) url.erase(0, 7); // Get the host name. string hst = url.substr(0, url.find('/', 0)); url.erase(0, url.find("/", 0)); // Connect to...
Some people report that WS can fail with this error if got pointer inside application stack memory. It looks like you are using VS2005 or newer where std::string has internal 16 chars long buffer - and exactly this buffer address was passed into gethostbyname(). Try to copy your string to heap before passing it to WS: ...
861,517
861,556
What issues can I expect compiling C code with a C++ compiler?
If you take an existing C code base and compile it with a C++ compiler, what sort of issues can you expect to crop up? For example, I think that assigning an integer to an value with an enumerated type will fail in C++, whereas it's legal (if a bit nasty) in C. If I don't wrap all my C files in extern C { ... }, am I g...
I've done something like this once. The main source of problems was that C++ is more strict about types, as you suspected. You'll have to add casts where void* are mixed with pointers of other types. Like allocating memory: Foo *foo; foo = malloc(sizeof(*foo)); The above is typical C code, but it'll need a cast in ...
861,532
861,649
Making all variables in a program modifiable at runtime by the programmer, smart idea?
I was thinking of doing this with C++, basically from an external editor or something the programmer can say: MyClass::dude = "hello" where 'dude' is a static integer in 'MyClass'. What the program does at runtime is it partitions the input to MyClass :: dude = "hello" and finds the class called 'MyClass' and assigns t...
Yes, this is a typical tool used during development to help fine-tune games. It's not so often something you type in as much as a screen where you can adjust variables on the fly with a controller (that changes some class variable under the hood), but for pc games, there isn't a reason why you couldn't type in somethin...
861,707
861,959
Is reducing number of cpp translation units a good idea?
I find that if there are a lot of classes the compilation time is dramatically increased when I use one *.h and one *.cpp file per class. I already use precompiled headers and incremental linking, but still the compile time is very long (yes I use boost ;) So I came up with the following trick: defined *.cpp files as ...
The concept is called unity build
861,832
861,848
validating CEdit without subclassing
Is there any way to validate the contents of a CEdit box without subclassing? I want to check for invalid filename characters in a CEdit box and not allow the user to input it at all (keypress should not be recorded, if pasted in the box, the invalid characters should just not make it to the edit box).. Is there any ea...
Per http://msdn.microsoft.com/en-us/library/f7yhsd2b(VS.80).aspx , "If you want to handle Windows notification messages sent by an edit control to its parent (usually a class derived from CDialog), add a message-map entry and message-handler member function to the parent class for each message." and "ON_EN_UPDATE The...
861,997
862,901
How to place a .net UserControl on a c++ cdialog in visual studio 6
My task is pretty simple create a .net usercontrol and use it in a old visual studio 6 proejct. I have createt the usercontrol (its just a user control with a label), I then followed this guide (http://support.microsoft.com/kb/828736) and it seems to work fine. But how can I display the usercontrol? Do I have to use Cr...
For something this simple, why not write your own class that inherits CWnd? Is there a reason the control needs to be a .Net UserControl? That said, the route I would take to host a .Net control on a VC++ 6 form would be to reverse-engineer the source of the VC++ 8 (VC++ 2005) CWinFormsUserControl class. If you have Vi...
862,051
908,186
What is the difference between ImageMagick and GraphicsMagick?
I've found myself evaluating both of these libs. Apart from what the GraphicsMagick comparison says, I see that ImageMagick still got updates and it seems that the two are almost identical. I'm just looking to do basic image manipulation in C++ (i.e. image load, filters, display); are there any differences I should be ...
From what I have read GraphicsMagick is more stable and is faster. I did a couple of unscientific tests and found gm to be twice as fast as im (doing a resize).