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
1,425,912
1,425,984
Google Protocol Buffers and HTTP
I'm refactoring legacy C++ system to SOA using gSoap. We have some performance issues (very big XMLs) so my lead asked me to take a look at protocol buffers. I did, and it looks very cool (We need C++ and Java support). However protocol buffers are solution just for serialization and now I need to send it to Java front...
You can certainly send even a binary payload with an HTTP request, or in an HTTP response. Just write the bytes of the protocol buffer directly into the request/response, and make sure to set the content type to "application/octet-stream". The client, and server, should be able to take care of the rest easily. I don't ...
1,426,093
1,426,126
Set vector type at runtime
I have a program that needs to set the type of a vector as the program is executed (according to a value in a configuration file). I have tried this: int a = 1 if(a == 1) vector<int> test(6); else vector<unsigned int> test(6); test.push_back(3); But this gives me: Error 1 error C2065: 'test' : undeclared ident...
The reason it does not work is that you're declaring the vectors inside the if- and else-block respectively, so they go out of scope once that block ends. Is there a way to decide the type of a vector at runtime similar to what I have attempted above? No, the type of a variable must be known at compile-time. Your onl...
1,426,403
1,431,357
Sending data between Java to c++ on windows?
I want to send the raw audio buffer to c++ for audio transcoding. I have two option using piped stream using direct buffers (java.nio) Are these really my 2 best options (and which would people recommend?) Thanks!
Direct buffers in NIO will almost certainly have better performance. This is pretty much the ideal case for direct buffers. I'm not sure what the point of your question is - if you want to know if there are other options, then the answer is certainly yet (you could, for example, write to a file then invoke an external...
1,426,562
1,426,581
Windows Magnification API, .NET and matrices
I'm trying to create a magnifier app in .NET using the Windows Magnification API. I've pretty much got everything working except for actually setting the magnification level (which defaults to 100%). The problem is, I can't find any examples anywhere on the Internet and all the documentation for the API is C++ code. ...
The memset is just clearing out the matrix to start with. You wouldn't need to do this in .NET. I suspect the simplest way of defining the struct in C# would be to specify each element individually: public struct MagTransform { readonly float m00; readonly float m10; readonly float m20; readonly float m...
1,426,665
1,430,104
Problem with HDN_ENDTRACK when resizing a list column
I am having a bit of a problem when handling a HDN_ENDTRACKW message for a custom class which derives from CListCtrl . Essentially, it seem that when this message is sent, the actual value which stores the width of the column is not updated until after my handling code has been executed. The code inside the handle sim...
Use the information that HDN_ENDTRACK itself provides to you, ie: void ProgListCtrl::OnEndTrack(NMHDR* pNMHDR, LRESULT* pResult) { NMHEADER *pHdr = (NMHEADER*) pNMHDR; if ((pHdr->iItem == m_nProgressColumn) && (pHdr->pitem) && (pHdr->pitem->mask & HDI_WIDTH)) { int width = pHdr->pite...
1,426,986
1,426,992
What does `*&` in a function declaration mean?
I wrote a function along the lines of this: void myFunc(myStruct *&out) { out = new myStruct; out->field1 = 1; out->field2 = 2; } Now in a calling function, I might write something like this: myStruct *data; myFunc(data); which will fill all the fields in data. If I omit the '&' in the declaration, this w...
The & symbol in a C++ variable declaration means it's a reference. It happens to be a reference to a pointer, which explains the semantics you're seeing; the called function can change the pointer in the calling context, since it has a reference to it. So, to reiterate, the "operative symbol" here is not *&, that combi...
1,427,002
1,434,508
Calling Py_Finalize() from C
This is a follow up to Call Python from C++ At the startup of the programm I call the following function to initialize the interpreter: void initPython(){ PyEval_InitThreads(); Py_Initialize(); PyEval_ReleaseLock(); } Every thread creates it's own data structure and acquires the lock with: PyGILState_STATE...
Yeah the whole section is rather dubious but I think I've got my mistake. I've got to save the PyThreadState when initializing the interpreter and swap this state back in when I finish it (no idea why I need a specific ThreadState to call Finalize - shouldn't every State work as well?) Anyways the example if other peop...
1,427,197
1,429,070
XAudio2 and variable bitrate audio
How do I go about correctly playing audio files which may have a variable bitrate (and even a variable number of channels in some cases), such as ogg/vorbis? XAudio expects this information in a WAVEFORMATEX structure on creation of the source voice, and doesn't seem to provide a means to change it for each buffer that...
Unless I'm high, no audio format specifies variable output bitrate or variable number of output channels. A variable bitrate codec means that the number of bits used to encode a fixed number of samples varies. Vorbis allows for dynamically encoding the channels as well for channels that can be reproduced with simpler f...
1,427,931
1,427,960
What is the most common way of understanding a very large C++ application?
When having a new C++ project passed along to you, what is the standard way of stepping through it and becoming acquainted with the entire codebase? Do you just start at the top file and start reading through all x-hundred files? Do you use a tool to generate information for you? If so, which tool?
I use change requests/bug reports to guide my learning of some new project. It never makes a lot of sense to me to try and consume the entirety of something all at once. A change order or bug report gives me guidance to focus on this one tendril of the system, tracing it's activity through the code. After a reasonable ...
1,428,117
1,428,542
Linux IPC - Multiple writers, single reader
I have never written any IPC C++ on Linux before. My problem is that I will have multiple clients (writers), and a single server (reader). All of these will be on the same machine. The writers will deliver chunks of data (a string/struct) to the reader. The reader will then read them in FIFO and do something with them....
The main issue you should consider is what kind of data you are passing as this will in part determine your options. This comes down to whether your data is bounded or not. If it isn't bounded then something stream oriented like FIFOs or sockets are appropriate; if it is then you might make better use of of things li...
1,428,130
1,428,136
Making a .exe in Visual Studio 2008
Could anyone be kind, and tell me how to make a exe file in visual studio 2008 for a win32 console based, c++ program? Thanks
Try using the Win32 Console Application type in the New C++ wizard. Building this will produce a native C++ executable application.
1,428,786
1,428,814
What is the best way to find a prime number?
what will be the best way to find a prime number so that the time complexity is much reduced.
When it comes to finding prime numbers, the Sieve of Eratosthenes and the Sieve of Atkin are two possible solutions. The Sieve of Eratosthenes has a complexity of O((n log n)(log log n)). The Sieve of Atkin has a complexity of O(N / log log n). If you have a number and you want to find out if it's prime, that is called...
1,428,972
1,430,182
Dynamic slicing in C/C++
After reading the book of debugging from Andreas Zeller, I became interested in Dynamic Slicing. At the moment I only found relevant tools for Java analysis. Do you know such tools for C/C++?
A little information in addition to Rob's the Wisconsin Program-Slicing Tool has evolved in a tool called CodeSurfer. Good news: it's commercially available and supported, and it works great for what it does. Bad news (perhaps): it does not actually produce a reduced program that computes the same value that you selec...
1,429,266
1,430,025
Customizing Win32's Save File Dialog
I am trying to save a file using GetSaveFileName and want to have a couple extra popups at the bottom of my save file dialog to allow the user to specify further options. I am trying to follow the MSDN documentation (specifically the Explorer-style customization) on the subject but can't seem to get my custom item to a...
When calling CreateWindowEx() to create your child window, you need to use GetParent() to get the parent window of the dialog, and then use that HWND as your parent window. Do not use the dialog itself as the parent. In other words: HWND settings_popup = ::CreateWindowExW(WS_EX_CLIENTEDGE | WS_EX_NOPARENTNOTIFY, ...
1,429,336
1,429,350
Cross referencing included headers in c++ program
I am curious about a scenario set up like the following example: Here is code that would be placed in a file called Header1.h: #ifndef HEADER1_H #define HEADER1_H #include "Header2.h" class Class1 { Class2 class2Instance; }; #endif Here is code that would be placed in a file called Header2.h: #ifndef HEADER2_H #de...
The problem is that the size of Class1 depends on Class2, and vice-versa. Therefore, there's no way to calculate the size for either one. Forward-declare one of the classes, and change one of the attributes to be a pointer or reference: #ifndef HEADER2_H #define HEADER2_H class Class1; class Class2 { Class1 *class1In...
1,429,440
1,429,500
C++ Class or Struct compatiblity with C struct
Is it possible to write a C++ class or struct that is fully compatible with C struct. From compatibility I mean size of the object and memory locations of the variables. I know that its evil to use *(point*)&pnt or even (float*)&pnt (on a different case where variables are floats) but consider that its really required ...
Yes. Use the same types in the same order in both languages Make sure the class doesn't have anything virtual in it (so you don't get a vtable pointer stuck on the front) Depending on the compilers used you may need to adjust the structure packing (usually with pragmas) to ensure compatibility. (edit) Also, you must...
1,429,472
1,429,514
Change speed of keystroke C++
Basically, when one types, a keydown event happens. If the key is held for more than a certain time (~1 sec) then the key is repeatedly pressed until keyup hapens. I would like to change the time it takes for the key to be automatically repressed in my c++ application. How can this be done? Thanks
The speed at which a keypress becomes automatically recurring is controlled by Windows. If you want to manipulate automatic recurrences of key-presses, it might be more advantageous to poll for the state of the key rather than waiting for the keydown event. It depends on how responsive you need your application to be....
1,429,659
1,429,722
Partial template specialization on a class
I'm looking for a better way to this. I have a chunk of code that needs to handle several different objects that contain different types. The structure that I have looks like this: class Base { // some generic methods } template <typename T> class TypedBase : public Base { // common code with template specia...
Impose another level of indirection in the template definitions: class Base { // Generic, non-type-specific code }; template <typename T> class TypedRealBase : public Base { // common code for template }; template <typename T> class TypedBase : public TypedRealBase<T> { // Inherit all the template functi...
1,429,666
1,429,682
What is the function of the ~ operator?
Unfortunately, search engines have failed me using this query. For instance: int foo = ~bar;
I'm assuming based on your most active tags you're referring to C#, but it's the same NOT operator in C and C++ as well. From MSDN: The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, lo...
1,429,735
1,450,290
Custom UserControls in C++
In Native C++, how do you add a usercontrol like in vb .net where you do form.controls.add(controls) Because for instance, what if I wanted to make a usercontrol class that inherits from panel? How is this done in c++ Thanks
You will want to use MFC (Microsoft Foundation Classes) for native C++ development. MFC is the original framework for Windows applications, long before .NET.
1,429,782
1,429,819
Qt and Sqlite examples
I am looking for some example code using Qt and it's SQL module with Sqlite driver. Main reason I need examples for is that I've prior experience with Qt's database interface and Sqlite has some weird behavior with field types (types are stored per-field, not per-column).
The Qt 5 SQL examples use SQLite as this does not require a database server. You should be able to go from the supplied examples to your own sample code pretty quickly.
1,429,850
1,431,221
Bringing libcurl into a C++ program
I'm trying to pull libcurl into a large C++ project. However I am having trouble getting it to compile. I see errors coming from ws2def.h, winsock2.h, and ws2tcpip.h Some of the errors look like this: error C2061: syntax error : identifier 'iSockaddrLength' ws2def.h 225 error C3646: 'LPSOCKADDR' : unknown override ...
Try including windows.h BEFORE you include winsock2.h or any libcurl headers. Don't ask my why this sometimes works, but it does.
1,430,026
1,430,038
What does sizeof(char *) do?
I was reading through the c++ Primer and this code snippet came up and I was wondering what does the sizeof(char *) do and why is it so significant? char *words[] = {"stately", "plump", "buck", "mulligan"}; // calculate how many elements in words size_t words_size = sizeof(words)/sizeof(char *); // use entire arr...
Because otherwise you would get the number of bytes that words array takes up, not the number of elements (char pointers are either 4 or 8 bytes on Intel architectures)
1,430,166
1,430,285
Vector Ranges in C++
Another quick question here, I have this code: string sa[6] = { "Fort Sumter", "Manassas", "Perryville", "Vicksburg", "Meridian", "Chancellorsville" }; vector<string> svec(sa, sa+6); for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); iter++) { std::cout << *iter <...
You have an array of only six elements. When you try to access the supposed "seventh" element, you get undefined behavior. Technically, that means anything can happen, but that doesn't seem to me like a very helpful explanation, so let's take a closer look. That array occupies memory, and when you accessed the element ...
1,430,495
1,430,813
Perform a simple HTTP request using C++ / Boost via a proxy?
I'm quite a newbie with Boost, and my only experience of surfing though a proxy using a library is using .NET (that is really convenient for that purpose). I'm now trying to perform a simple HTTP request through a HTTP proxy. Is there a tidy way to do it using boost directly? My proxy use a NTLM authentification.
No, Boost provides neither an HTTP client nor a way to interface with proxies. You would necessarily have to implement those features yourself. To be clear, yes, it is possible to implement an HTTP client using Boost.Asio. But implementing a client that can reliably talk through a proxy is significantly more complex, a...
1,430,681
1,430,755
Creating dummy shared object (.so) to depend on other shared objects
I'm trying to create a shared object (.so) that will make it so, by including one shared object with -lboost, I implicitly include all the boost libraries. Here's what I tried: #!/bin/sh BOOST_LIBS="-lboost_date_time-gcc43-mt -lboost_filesystem-gcc43-mt" #truncated for brevity g++ $BOOST_LIBS -shared -Wl,-soname,lib...
You don't. Not really, anyway. The linker is stripping out all of the symbol dependencies because the .so doesn't use them. You can get around this, perhaps, by writing a linker script that declares all of the symbols you need as EXTERN() dependencies. But this implies that you'll need to list all of the mangled names ...
1,430,757
1,430,774
Convert a vector<int> to a string
I have a vector<int> container that has integers (e.g. {1,2,3,4}) and I would like to convert to a string of the form "1,2,3,4" What is the cleanest way to do that in C++? In Python this is how I would do it: >>> array = [1,2,3,4] >>> ",".join(map(str,array)) '1,2,3,4'
Definitely not as elegant as Python, but nothing quite is as elegant as Python in C++. You could use a stringstream ... #include <sstream> //... std::stringstream ss; for(size_t i = 0; i < v.size(); ++i) { if(i != 0) ss << ","; ss << v[i]; } std::string s = ss.str(); You could also make use of std::for_each i...
1,430,804
1,430,924
looking for a keyboard API
looking for a library for accessing the keyboards functions, key states, etc. the language I'm planning on using is C++
There is no such possibility in C++ standard. It depends on platform you are going to support. The only portable way is to use portable library. You could try Qt library, which is good looking and pretty convenient. For console application you could try ncurses.
1,430,907
1,430,922
Help in combining two functions in c++
I am just trying something with somebody else's code. I have two functions: int Triangle(Render *render, int numParts, Token *nameList, Pointer *valueList) int i; for (i=0; i<numParts; i++) { switch (nameList[i]) { case GZ_NULL_TOKEN: break; case GZ_POSITION: ...
If you just change the line return putTrianglePosition(render, (Coord *)valueList[i]); into: Coord* vertexList = (Coord*) valueList[i]; followed by the whole body of what's now putTrianglePosition from the opening { to the closing } included, I believe it should just work. If not, please edit your questio...
1,430,935
1,430,977
How to set different timeouts for each socket that select() monitors?
I am currently using the BSD sockets API. I would like to use the select() function to monitor (a) the listener socket which waits for new connections using accept(), and (b) all the client sockets created via accept() or connect(). I want the listener socket to not have any timeout, and I want each client socket to ha...
Due to the logic of select() function, you should pass it minimal timeout of your ones. If this minimal timeout is hit, then the corresponding socket is timeouted and you should handle this situation. In other words, sockets with greater timeouts can never timeout, because they just wont' have chance to: the time is ...
1,431,144
1,431,171
How to output floating point numbers in the original format in C++?
It's a coding practice. I read these numbers as double from a file: 112233 445566 8717829120000 2.4 16000000 1307674.368 10000 2092278988.8 1234567 890123 After some computation, I should output some of them. I want to make them appear just the same as in the file, no filling zeros, no scientific notation, how could I ...
If you want the output to be identical to the input, then yes, you need to read them in as strings and store the strings to be output later. Why? When dealing with floating point numbers, the computer can't represent most decimal fractional parts exactly in binary. So in a number like 2.4, the internal representation w...
1,431,216
1,431,241
What is the difference between PostMessage and AfxBeginThread?
I can acheive the same functionality by both PostMessage and AfxBeginThread ( calling asynchrously ) So where lies the the difference between PostMessage and AfxBeginThread?
AfxBeginThread starts a whole new thread in your function. PostMessage is using the main message loop of the process, so if you use PostMessage to do a long operation, you will freeze the message loop, making the GUI non responsive till you finish the operation.
1,431,560
3,702,932
How to detect Oracle broken/stalled connection?
In our server/client-setup we're experiencing some weird behaviour. The client is a C/C++-application which uses OCI to connect to an Oracle server (using the OTL library). Every now and then the DB server dies in a way (yes this is the core issue, but from application-side we're unable to solve it but have to deal wit...
This is a bug in Oracle ( or call it a feature ) till 11.1.0.6 and they said the patch on Oracle 11g release 1 ( patch 11.1.0.7 ) which has the fix. Need to see that. If it happens you will have to cancel ( kill ) the thread performing this action. Not good approach though
1,431,567
1,431,606
Is it possible to load a NPAPI plugin in Safari (Mac OS X)?
I've got some code that lies in a browser, and wrote C++ plugins for both IE (COM/ActiveX) and firefox (NPAPI). I now have to get this code work on Mac OS X. I found some input on apple's site, but it's written in Objective C. I also read about SIMBL, but it seems to deal with Objective C code only, isn't it? So here a...
The NPAPI plugin mechanism is the standard mechanism for browser plugins on MacOS (and linux -- everything other than IE really) -- if you use the NPAPI your plugin will work on Safari, Firefox, and Opera. They will also work in both 32 and 64-bit Safari. Assuming your code makes no assumptions about what browser it'...
1,431,598
1,431,642
BSTR and SysAllockStringByteLen() in C++
I'm new to C++, so this may be a noobish question; I have the following function: #define SAFECOPYLEN(dest, src, maxlen) \ { \ strncpy_s(dest, maxlen, src, _TRUNCATE); \ dest[maxlen-1] = '\0...
SysAllocStringByteLen is meant for when you are creating a BSTR containing binary data, not actual strings - no ANSI to unicode conversion is performed. This explains why the debugger shows the string as containing apparently chinese symbols, it is trying to interpret the ANSI string copied into the BSTR as unicode. Yo...
1,432,336
1,432,393
how to find a window's SW_SHOW/SW_HIDE status
I am trying to determine a window control's visibility that has been hidden or enabled with CWnd::ShowWindow(). (or ::ShowWindow(hWnd,nCmdShow)) I cannot simply use ::IsWindowVisible(hWnd) as the control is on a tab sheet, which may itself be switched out, causing IsWindowVisible to return FALSE. Is there a way to get ...
Use GetWindowPlacement. It fills WINDOWPLACEMENT structure, which has field showCmd. showCmd Specifies the current show state of the window. This member can be one of the following values.
1,432,419
1,432,446
How can I code in C++ with the same indentation style both in Vi and Emacs?
How can two developers work on a same C++ code base such that they can work transparently ? Is there any common indentation style for C++ code such that once it is established, the two developers can produce code with the same indentation level. I have found Emacs very aggressive for Indentation, it tries to force it...
Get Emacs to do what you want. From my ~/.emacs file: (defun my-c-mode-common-hook () (local-set-key "\C-h" 'backward-delete-char) ;; this will make sure spaces are used instead of tabs (setq tab-width 4 indent-tabs-mode nil) (setq indent-tabs-mode 'nil) (setq c-basic-offset 4) (c-set-offset 'substatement-o...
1,432,777
1,432,814
Using shared libraries vs a single executable
My colleague claims that we should dissect our C++ application (C++, Linux) into shared libraries to improve code modularity, testability and reuse. From my point of view it's a burden since the code we write does not need to be shared between applications on the same machine neither to be dynamically loaded or unloade...
I'd say that splitting code into shared libraries to improve without having any immediate goal in mind is a sign of a buzzwords-infested development environment. It is better to write code that can easily be split at some point. But why would you need to wrap C++ classes into C-function interfaces, except for, maybe, f...
1,433,278
1,433,727
How to write a generic "getData" function?
I have a class, say, "CDownloader", that reads some XML data and provides access by node names. It features some getter functions, something like this: BOOL CDownloader::getInteger ( const CString &name, int *Value ); BOOL CDownloader::getImage ( const CString &name, BOOL NeedCache, CImage *Image ); BOOL CDownloader:...
As long as you have three differently named functions and need to pick one depending on the type, at some point you have to have either an overload or some traits class to picks the right one. I don't think there's a way around that. However, since the call to one of these function is the only thing that needs this, if...
1,433,345
1,433,352
or is not valid C++ : why does this code compile?
Here is a very simple C++ application I made with QtCreator : int main(int argc, char *argv[]) { int a = 1; int b = 2; if (a < 1 or b > 3) { return 1; } return 0; } To me, this is not valid C++, as the keyword or is not a reserved keyword. But if I compile and run it, it works fine with...
According to Wikipedia: C++ defines keywords to act as aliases for a number of symbols that function as operators: and (&&), bitand (&), and_eq (&=), or (||), bitor (|), or_eq (|=), xor (^), xor_eq (^=), not (!), not_eq (!=), compl (~). As MadKeithV points out, these replacements came from C's iso646.h, and...
1,433,389
2,590,365
How to integrate the Qt libraries in SparxSystems Enterprise Architect
I like to know how one can integrate the Qt libraries into an Enterprise Architect project. I do not know if it is possible at all but I tried it with partial success: I added a new package to my project tried to import qt through Context Menu / Code Engineering / Import Source Directory and started with the directory ...
I turned to support@sparxsystems.com.au , their answer: "Thank you for your enquiry. No, unfortunately there is no easy way to integrate Enterprise Architect with Qt at this time. With most frameworks, we typically recommend reverse engineering the framework into Enterprise Architect, allowing you to reference the clas...
1,433,629
1,433,660
How to stop a new form from using namespace System::Collections
If I create a new form called myForm, the top of myForm.h looks like this: #pragma once using namespace System; using namespace System::ComponentModel; using namespace System::Collections; //<<<< THIS ONE using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; None o...
You can change the default templates that Visual Studio uses by editing the zip files in the ItemTemplates directory for the specific language that you use. C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033 is where the C# templates are. I'm assuming the C++ templates would be in...
1,433,632
1,433,643
Is there a Findbugs and / or PMD equivalent for C/C++?
I was recently asked about alternatives to Coverity Prevent for a code base that includes both C/C++ and Java. Obviously, on the Java side, the free tools available include Findbugs (compiled code analysis) and PMD (static code analysis). They are very powerful, especially when you start investigating integration wit...
The two that come to mind are Splint for C and Cppcheck for C++. If you want to look for more options, this function of these tools is "static code analysis". That might help you find more tools for C and/or C++. Also, you might be interested in the answer to the question "What open source C++ static analysis tools are...
1,433,850
1,434,105
QFontMetrics::leading() returns 0
Why next function returns 0 ? (My environment is: Windows Vista, vc++9, Qt4.5) int func() { QPushButton button("Blah blah"); QFontMetrics fm = button.fontMetrics(); return fm.leading(); } Calling to "fm.height()" returns reasonable results (16 px in my case). Calling to "fm.lineSpacing()" returns same r...
According to the docs lineSpacing() is always equal to height() + leading() height() is always equal to ascent()+descent()+1 (the 1 is for the base line). From here leading is "the space vertically between lines of text - name comes from the physical piece of lead that used to be used in mechanical printing process to ...
1,433,855
1,433,896
Is there an easy way to find two values that, when multiplied together, produce an exact bit pattern?
For testing purposes, I need to find two 64-bit integer values that exactly multiply to a 128-bit intermediate value with a specific bit pattern. Obviously, I can generate the desired intermediate value and divide by random values until I find a combination that works, but is there a more efficient way?
This problem sounds like integer factorisation. No fast algorithms are known unfortunately, but from glancing at that Wikipedia page it seems there are some (possibly tricky) algorithms that are faster than trial division.
1,434,343
1,434,438
How do i sort objects?
I've created a class and created an array of objects under that class and filled it all up with data. Now i want to sort the entire array by a specific member of that class, how do I do this using the stable_sort() function? Edit: Ok, i have this right now, class sortContiner { public: double position; int ke...
You need iterators into your array and some sorting criterion. Let's start with the iterators: You will need a begin iterator and an end iterator. The begin iterator needs to point to the first element, the end iterator needs to point behind the last element. Pointers are perfect iterators. An array is implicitly conv...
1,434,437
1,434,482
How do you disassemble an overloaded operator in gdb?
If I have something like bool operator ==(const uint128& x, const uint128& y); how can I get gdb to disassemble it?
(gdb) p 'operator==(uint128 const&,uint128 const&)' $1 = {bool (const uint128 &, const uint128 &)} 0x401040 <operator==(uint128 const&, uint128 const&)> (gdb) disassemble $1 Dump of assembler code for function _ZeqRK7uint128S1_: 0x00401040 <_ZeqRK7uint128S1_+0>: push %ebp ... (elided) 0x00401066 <_ZeqRK7uint128...
1,434,511
1,476,192
How do I convert double to string using only math.h?
I am trying to convert a double to a string in a native NT application, i.e. an application that only depends on ntdll.dll. Unfortunately, ntdll's version of vsnprintf does not support %f et al., forcing me to implement the conversion on my own. The aforementioned ntdll.dll exports only a few of the math.h functions (f...
After a lot of research, I found a paper titled Printing Floating-Point Numbers Quickly and Accurately. It uses exact rational arithmetic to avoid precision loss. It cites a little older paper: How to Print Floating-Point Numbers Accurately, which however seems to require ACM subscription to access. Since the former pa...
1,435,004
1,435,059
variable-size type declared outside of any function
when declaring the two dimensional array int random[height][width]; and then using it in a function void populate(int random[height][width], int x, int y) gives the error variable-size type declared outside of any function. I know I'm doing something wrong, and that its something small. I just have a bad memory...
I'm going to step up right now and tell you that multidimensional arrays are not worth the brain effort in C or C++. You're much better off using single-dimensional arrays (or, better yet, standard containers) and writing an indexing function: inline int index (int x, int y) { return x + y * width; } Now for your pr...
1,435,541
1,435,568
is this function reentrant?
void reverse_string(char* string, int str_size) { char tmp; int i = 0; int j = str_size - 1; while (i < j) { tmp = string[i]; string[i] = string[j]; string[j] = tmp; ++i; --j; } } I think this function is reentrant, since it doesn't use any global variable. I...
Yes, this is a reentrant function. Reentrant functions are defined as those that can be called whilst they are themselves executing (either due to recursion, or concurrency). In this case, recursion is moot, and you are concurrently safe (assuming differing parameters). Your argument is fine - there's no global or shar...
1,435,766
1,435,782
C Variable Scope Specific Question
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main()...
Is it because the "=" on the line s.t = x; copies the values of x into s.t? Yes. By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".
1,435,911
1,435,925
C++ Process Checking
I'm creating a task-manager type application in C++, and I'm currently using: ` void MyFrame::ProcChecker(bool showmessage=false){ HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); PROCESSENTRY32 *processInfo = new PROCESSENTRY32; processInfo->dwSize = sizeof(PROCESSENTRY32); int index = 0; strin...
In order to query information about processes that you don't directly have access to, you need to have SeDebugPrivilege*. If this is on Vista, you most likely are running as standard user and you don't have that privilege. You need to run your program as administrator (note that TaskManager has to run as admin to get...
1,436,020
1,436,038
What's the difference between deque and list STL containers?
What is the difference between the two? I mean the methods are all the same. So, for a user, they work identically. Is that correct??
From the (dated but still very useful) SGI STL summary of deque: A deque is very much like a vector: like vector, it is a sequence that supports random access to elements, constant time insertion and removal of elements at the end of the sequence, and linear time insertion and removal of elements in the middle. The ma...
1,436,219
1,436,248
structure initialization
static struct Args { char* arg1; unsigned arg2; unsigned arg3; char* arg4; } arg; My program saves command line args to a structure. Sometime all of the members are set... sometimes only a couple of them. In the case where only arg1 is set, what would the best practice be to do with the rest of the members?...
I would just memset the whole thing. Any 0 value or null pointer are assumed not set. For example, memset(&arg, 0, sizeof(arg)); ... if (arg.arg2 == 0) // Not set
1,436,271
1,436,303
In MFC program, how to pass data between different dialog?
In web development, when we want to pass something between different pages, we might use the Session to save the data. But in MFC, what can we use to store these things? Thanks!
Typical MFC Applications will have a Document-View-Frame architecture. Data is stored in the Document object, and accessed globally. You can access it anywhere via AfxGetMainWnd(). AfxGetApp() will also get you a pointer to your main application, which is another good spot to store data if you're not using a Document ...
1,436,300
1,436,332
in mfc how to implement dockable dialog?
i am working on a Dialog based application in MFC, I need something just like visual studio's left panel, right panel, bottom panelwhich have a close button to close the panel. Anyone know how to implement this ?
Try the MFC Feature Pack.
1,436,326
1,436,531
cmath Errors when using FLTK
For some reason, whenever I add the FLTK directory to my include path, I get a bunch of errors from cmath. I am using GCC version 4.2. Here is a sample program and the build output: main.cpp #include <cmath> int main() { return 0; } **** Build of configuration Debug for project CMath Test **** make -k all Bu...
Pure speculation, but is there a 'math.h' header in /usr/include/FL by any chance? Or is there some other header in there that is included by cmath? [...a little time passes...] Still speculation, but given the comment "Yes, there is - what's going on?", I will speculate that there is no 'math.h' header in /usr/includ...
1,436,351
1,436,751
How many threads does it take to make them a bad choice?
I have to write a not-so-large program in C++, using boost::thread. The problem at hand, is to process a large (maybe thousands or tens of thousands. Hundreds and millons are a possibility as well) number of (possibly) large files. Each file is independent from another, and they all reside in the same directory. I´m th...
According to Amdahl's law that was discussed by Herb Sutter in his article: Some amount of a program's processing is fully "O(N)" parallelizable (call this portion p), and only that portion can scale directly on machines having more and more processor cores. The rest of the program's work is "O(1)" sequential (s). [1,...
1,436,374
1,438,819
getpeername() doesn't work with connections to localhost
EDIT: Restating the problem, if I am listening to port 54321 and a local process listening to port 12345 connects to me, creating socket s, how do I actually find the port it is listening on? sockaddr_in addr; int len = sizeof(addr); getpeername(s, (sockaddr*)&addr, &len); cout << string(inet_ntoa(addr.sin_addr)) << ":...
It looks like you have two processes listening on two ports - that's two listening sockets independent of each other. Then you create a third, client, socket in one of the processes and connect to the other one. That third socket gets an ephemeral port assigned to it by TCP stack (62305 in your case). So the connection...
1,436,617
1,436,630
Is there any relation between Virtual destructor and Vtable
If we write virtual function it adds a vtable in object of that class. Is it true for virtual destructor too ? Is vtable used to implement virtualness of destructor
Yes. Some information is needed to allow the right destructor to be called when the object is deleted via a base class pointer. Whether that information is a small integer index or a pointer doesn't matter (although dynamic linkage probably implies that it's a pointer). Naturally, that information needs to be adjace...
1,436,737
1,437,036
What's your deep comprehension of pointer,reference and Handle in C,C++ and Java?
What's your deep comprehension of pointer,reference and Handle in C,C++ and Java? We usually think about the pointer,reference and Handle on the specify language level, it's easy to make confusion by the newbie like me. Actually all those concept in java, just a encapsulation of pointer. All pointer just a encapsulati...
Each language has differences to this respect. In C there are only pointers that are variables holding a memory address. In C you can use pointer arithmetic to move through memory, if you have an array, you can get a pointer to the first element and navigate the memory by incrementing the pointer. Java references are ...
1,436,968
1,437,115
Variadic function without specified first parameter?
Out of curiosity, I thought I'd try and write a basic C++ class that mimics C#'s multiple delegate pattern. The code below mostly does the job, with the nasty sacrifice of losing almost all type-safety, but having to use the initial dummy parameter to set up the va_list really seems a bit off. Is there a way to use va_...
Functions with ellipsis in C++ is only for compatibility with C. Using C++ I'd return temporary helper object in Call function and add template operator% to pass variable number of arguments. To use it in the following way: cDelegateCaller.Call() % 2 % "Hello" % sString; // dummy argument isn't required As to your que...
1,437,053
1,437,748
Boost advocacy - help needed
Possible duplicates Is there a reason to not use Boost? What are the advantages of using the C++ BOOST libraries? OK, the high-level question is "Please provide me with what you consider to be the most effective arguments of why entire Boost, or some specific parts of it, should be compiled on our company's system an...
Wherever I worked in the last decade, when they had their own smart pointer class, I found bugs in that - usually within a few weeks. And, no, I never went and looked at it hoping to find errors. I got into the habit of posting the following quote from the TR1 smart pointer proposal: The Boost developers found a shar...
1,437,184
1,437,248
Virtual inheritance - gcc vs. vc++
I have a problem with Visual Studio 2008 concerning virtual inheritance. Consider the following example: #include<iostream> class Print { public: Print (const char * name) { std::cout << name << std::endl; } }; class Base : public virtual Print { public: Base () : Print("Base") {} }; cl...
From the standard [class.base.init]: "Unless the mem-initializer-id names a nonstatic data member of the constructor’s class or a direct or virtual base of that class, the mem-initializer is ill-formed." Evidently gcc interprets your case as legal as Print is a non-direct, but virtual base of B, however MSVC 2008 doesn...
1,437,327
1,437,364
Saving to disk an in-memory database
I made a database through sqlite in c++. The db has been created in memory (using the ":memory:" parameter insted of a filename), in order to have a very quick behavior. The database is created by the following lines: sqlite3* mem_database; if((SQLITE_OK == sqlite3_open(":memory:", &mem_database)){ // The db has b...
Check out this example: Loading and Saving In-Memory Databases
1,437,337
1,437,348
Specification on C++ and C#?
If you want to read the "source" of a language in C you go to C Programming Language by Kernighan; Ritchie; 0131103628 And in Java you read Goslings The Java(tm) Language Specification; 0321246780 But what do you read if you want to read a good book about the "specs" on C++ and C#?
C++: Stroustrup's book and/or Stroustrup's D&E or Stroustrups ARM though the latter two are not in date. The ISO spec is available (see Charles bailey's answer) and is the final word if that's the type of doc you want. The most thorough answer is in the comments by aJ :- The Definitive C++ Book Guide and List. The equi...
1,437,417
1,437,639
Is it possible to use Qt threading without inheriting any Qt object?
The only way to enable threading demonstrated in qt documentation is through inheriting QThread and then override its run() method. class MyThread : public QThread { public: void run(); }; void MyThread::run() { QTcpSocket socket; // connect QTcpSocket's signals somewhere meaningful ... s...
You can use multithreading without inheriting from QObject with QtConcurrent::run(): QFuture QtConcurrent::run ( Function function, ... ) Runs function in a separate thread. The thread is taken from the global QThreadPool. Note that the function may not run immediately; the function will only be run when a thread is...
1,437,450
1,440,923
Windows Limited User Installation
I have a Win32 application that includes an EXE, an ActiveX control (DLL) and a COM server (EXE) and I am using Inno Setup 5 to build my installer. Many of our customers use limited user accounts where the user has no admin rights and because the COM components require to be registered (which writes to HKEY_CLASSES_RO...
I don't know for sure, but I seem to recall COM servers support per-user installation, and maybe that goes for EXE servers as well. If so, change your registration code to write information to HKEY_CURRENT_USER\Software\Classes instead of HKEY_CLASSES_ROOT. The COM infrastructure should do the lookup first per-user and...
1,437,816
1,437,853
Sort vectors by last elements
Have a "vector of vectors" that looks something like this 3 1 2 0 77 0 3 1 2 44 1 0 3 2 29 3 0 1 2 49 I would like to sort them according to the last element in every row so that it would look like this in the end 1 0 3 2 29 0 3 1 2 44 3 0 1 2 49 3 1 2 0 77 Of course my real example is a lot more complex... but this...
You can use std::sort with a function (or functor object) that provides a strict weak ordering for vectors. I.e. you define a vector-less-than function that orders two vectors correctly, something like this (off the top of my head). Edit: after comments, added checking for one or two empty vectors, which does make thi...
1,438,038
1,465,440
Writing to binary file in C++ and C#
I have 2 applications. One in C++ (windows) open a binary file and only reads from it, i use: fstream m_fsDataIN.open("C:\TTT", ios::in | ios::binary | ios::app); and the second application (is in C#) opens the file and writes to it. I use: byte[] b = ... //have a binary data System.IO.BinaryWriter bw = new System.IO...
The problem was in the C++ application. The program contained configuration which produced another file handler. Using Process Explorer I found out about it. Removing the configuration of that extra file handler resolved the problem.
1,438,053
1,438,080
Converting old C code to work with threads
I have a very old, very very large, fully working, C program which plays a board game. I want to convert it (or should I say parts of it) to work in multiple threads, so that I can take advantage of multi-core processors. In the old program there is a global UBYTE array called board[]. There are a great many (highly op...
If you don't need to merge thread result boards back in the same one, looks to me like a good strategy, making each thread have their own copy of the board and working on it, I don't see why it shouldn't work. However, looks to me like the threads will perform a lot of cpu-bound operations, if thats true, you shouldn't...
1,438,285
1,438,293
C++ iterators breaking in Visual C++ but not GNU g++
I am trying to learn more about list containers and how to iterate through them, but it seems that g++ has no problem with it, but Visual Studio C++ pukes all over the place! #include <iostream> #include <string> #include <list> using namespace std; int main(){ list <string> data; list <int>::iterator it; ...
Try list<string>::iterator instead of list<int>::iterator.
1,438,901
1,447,747
does borland compiler fail when we try to compile a large data case
if yes.. then which compiler is best for compiling them?
may be it is trying to write on read only memory. try using next higher version of borland
1,439,165
1,441,492
Is anybody having problems inputing strings in Xcode 3.2?
For some reason excode is throwing this error when I try to cin into a string. test(5640) malloc: * error for object 0x1000041c0: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Program received signal: “SIGABRT”. sharedlibrary apply-load-rules all Here is the code that ...
According to this forum: http://discussions.apple.com/message.jspa?messageID=10236050#10236050 Technically, that is a warning message, not an error. This is a bug in the GCC C++ library. Remind me again why I don't write C++ code anymore. You would think in 2009 they would have silly things like this fixed. You could a...
1,439,172
1,439,265
testing code in C C++
I don't know how you guys test your code every time you code a little and for different levels of testing: unit testing, Integration testing, ... For example, for unit testing a function you just wrote, do you write another whole set of main function and Makefile to test it? Or do you modify the main function of your p...
xUnit is a family of unit testing modules. x is replaced by a letter for the language of framework used. The family currently consists of: CUnit (for C) CppUnit NUnit (.NET) EmbUnit ; embedded unit test for C I've worked in projects using CppUnit with good results. Recently I've tried to integrate this in an automat...
1,439,187
1,439,462
modify values of elements of an array in gdb for C++
Just wonder how to modify the values of multiple elements of an array under gdb for C++? Thanks and regards!
Something like: print memcpy (the_array_you_want_to_modify, {newvalue1, newvalue2, ..., newvalueN}, N * sizeof(the_array_you_want_to_modify[0])) may be what you're looking for?
1,439,455
1,439,472
C++ Events/Notifications & Default handling method list
Is there a list any where of C++ Events/Notifications & Default handling method list. For example, it would be useful to know that by default, the HDN_DIVIDERDBLCLICK notification is normally handled by the CWnd::OnLButtonDblClk method. This would make it easier to find the correct method when wanting to call it when ...
This page at MSDN lists the WM_XXX messages and the signatures of the corresponding handler methods. For notification messages that are emitted by controls, you'll want to look on the documentation page for the control. So, for example, the documentation for HDN_DIVIDERDBLCLICK is on the reference page for CHeaderCtrl...
1,439,508
1,440,638
Store QList<T> in QVariant and stream to QDataStream?
Here's the demo code: QList<Custom> L; QVariant v(QVariant::fromValue(l)); QDataStream d; d << v; The problem seems to be that d doesn't know how to stream v, because v doesn't know how to do a metatype save on L. I have registered Custom and L as metatypes and I've also registered their IO streams, but L has no meta ...
You need to register output operators for the given type. See also a similar question on QtCentre. What this implies is that you need to define non-member output operators matching the signature defined in the documentation and then call qRegisterMetaTypeStreamOperators.
1,439,959
1,440,307
distinguishing between static and non-static methods in c++ at compile time?
For some tracing automation for identifying instances i want to call either: a non-static method of the containing object returning its identifier something else which always returns the same id My current solution is to have a base class with a method which() and a global function which() which should be used if not...
You might be able to to use is_member_function_pointer from the Boost TypeTraits library. sbi's suggestion of using different code in the static and non-static cases is probably better though.
1,440,118
1,440,163
programmatically check for subsystem
I have a .exe created with a windows subsystem. I copy that .exe to another .exe, and I run: editbin.exe /SUBSYSTEM:CONSOLE my.exe So my intention is to have a .exe that runs with a GUI, and another .exe that is meant for command line operations (no GUI). How do I check what subsystem is currently active in my C++ co...
Subsystem type (GUI, console, etc.) is stored in the PE header, which you can access via the ImageHlp functions. You can get it with the following code: // Retrieve the header for the exe. GetModuleHandle(NULL) returns base address // of exe. PIMAGE_NT_HEADERS header = ImageNtHeader((PVOID)GetModuleHandle(NULL)); if ...
1,440,222
1,440,231
Constructors with default parameters in Header files
I have a cpp file like this: #include Foo.h; Foo::Foo(int a, int b=0) { this->x = a; this->y = b; } How do I refer to this in Foo.h?
.h: class Foo { int x, y; Foo(int a, int b=0); }; .cc: #include "foo.h" Foo::Foo(int a,int b) : x(a), y(b) { } You only add defaults to declaration, not implementation.
1,440,285
1,440,308
How to detect hot plugging of monitor in a win32 application?
I need some kind of event from Windows whenever there is a monitor that's getting plugged into system. Is there any API in Windows to do that. BTW, it is an C++ application
Use RegisterDeviceNotification to register for getting WM_DEVICECHANGE notification.
1,440,287
1,440,328
How to create a container of noncopyable elements
Is there a way use STL containters with non-copyable elements? something like this: class noncopyable { noncopyable(noncopyable&); const noncopyable& operator=(noncopyable&); public: noncopyable(){}; }; int main() { list<noncopyable> MyList; //error C2248: 'noncopyable::noncopyable' : cannot access pri...
No, non-copyable elements can't be in C++ container classes. According to the standard, 23.1 paragraph 3, "The type of objects stored in these components must met the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types."
1,440,324
1,440,338
Application configured incorrectly error C++
I'm new to c++. I made a c++ program using VS 2008 Professional. I started with the Win32 template that created a window for me. I compiled it on Vista 32. I brought the compiled exe to my old XP sp2 computer, and it tells me the application configuration is incorrect. Is there something im doing wrong? How do I make i...
Try installing Microsoft Visual C++ 2008 SP1 Redistributable Package and make sure you use the release build of your application.
1,440,418
1,440,544
Why don't member function temporaries bind to the right type?
Suppose that we have the following base and derived classes: #include <string> #include <iostream> class Car { public: void Drive() { std::cout << "Baby, can I drive your car?" << std::endl; } }; class Porsche : public Car { }; ..and also the following template function: template <typename T, typename V> void Fu...
int main(int argc, char** argv) { void (Porsche::*ptr)(void) = &Porsche::Drive; Function(&Porsche::Drive, ptr); return 0; } ptr has type void (Porsche::*)(), but &Porsche::Drive has type void (Car::*)() (because the member is found in Car, not in Porsche). Thus the function called compares these two member...
1,440,468
1,440,601
Set debugging macro conditionally with make
In my C++ project, I have a convention where whenever the macro DEBUG is defined, debugging printf-esque statements are compiled into the executable. To indicate whether or not I want these compiled into the executable, I normally would pass the macro name to gcc with the -Dmacro option. So, in the Makefile I (current...
You can conditionally define other variables based on the target in the makefile. all: target debug: target debug: DEBUG=PLOP target: @echo "HI $(DEBUG)" So now: > make HI > > make debug HI PLOP >
1,440,581
1,440,589
Enum and their Values
What would be the value of Field.Format("%04d", ErrorCode) in the procedure below if the AErrorCode is ERR_NO_HEADER_RECORD_FOUND_ON_FILE? Somewhere in a .h file: enum AErrorCode { ERR_UNKNOWN_RECORD_TYPE_CODE = 5001, ERR_NO_HEADER_RECORD_FOUND_ON_FILE, ERR_DUPLICATE_HEADER_RECORD_FOUND, ERR_THIRD_PART...
ERR_NO_HEADER_RECORD_FOUND_ON_FILE == 5002 If you don't specify any value at all, it starts at 0 and increments the next element in the enum. If you specify a value, then it starts incrementing starting by the next element. Unless you reset the counter again by specifying another value for a successor element.
1,440,689
1,440,730
windows process management
Why does the root directory of a process, started by a windows process manager, change to the directory of where the pm is located? Using msdn process manager code to create a pm service to run a few exes. The exes save log files in the root relative to their location. When started by the process manager, they are sav...
Tosses 'should be on superuser!!!' shield The PM is a process itself started from wherever the PM shortcut points to, so the WD will be the location of the executable. If you start another process from that, it will fork (errr, windows equivelent) another process with the same WD. If you think about it, what else would...
1,440,767
1,440,865
Cross-platform development?
I am looking for a solution which would allow me to code for Linux and Windows using C++. On Windows I use Visual Studio (I tried other stuff on Windows but I work with DirectX and as far as I know, it's the best solution). On Linux I use NetBeans (which I like very much). My problem is that I want the project be indep...
You should take the time to learn CMake and to speed up the learning process buy/read "Mastering CMake 4th Edition" If you have problems you should use the CMake mailing list, which is active (August 2009 had ~600 messages)
1,440,768
1,440,802
Initializing a polygon in boost::geometry
I am new to the generic geometry library that is proposed for inclusion with boost: http://geometrylibrary.geodan.nl/ I have two vectors vector<int> Xb, Yb that I am trying to create a polygon from. I am trying to get something along the lines of the following code snippet: polygon_2d P; vector<double>::const_itera...
append(P, make<point_2d>(*xi, *yi));
1,440,901
1,440,948
Question on DLL Exporting/Importing and Extern on Windows
I have some quick questions on windows dll. Basically I am using the ifdefs to handle the dllexport and dllimport, my question is actually regarding the placement of the dllexports and dllimports as well as extern keyword. I am putting the dllimports/dllexports on the header files but do I have to put the dllexport and...
First, you don't need to import or export typedefs. As long as they're in the header files that both sides use, you're good. You do need to import/export functions and class definitions. Presumably you use the same header files for both the importing and exporting code, so you could do some makefile magic to define a p...
1,440,977
1,441,022
How can you calculate the percentage overlap of two rectangles?
I wrote a drawing function that draws various on-screen sprites. These sprites can only overlap up to a point. If they have to much overlap, they become too obscured. As a result I need to detect when these sprites are too much overlapped. Luckily, the problem is simplified in that the sprites can be treated as orthogo...
The results depends on how you define overlapping percentage, to keep it symmetric, I would code it like this: double CalculatePercentOverlap(const wxRect& rect1, const wxRect& rect2) { wxRect inter = rect1.Intersect(rect2); if (inter.IsEmpty()) return 0; return (double)(inter.GetWidth()*inter.GetHeight()) * ...
1,441,143
1,443,562
How to set the line where a QToolBar is displayed?
I would like to ask if anyone knows how to display 2 QToolBars in two lines, one on top of the other? I found the class QStyleOptionToolBar, but I don't know how to use it... It is easy to drag one toolbar with the mouse to be placed below the other, so I think there must be a way how this can be done from the source c...
Try calling QMainWindow::addToolBarBreak(Qt::ToolBarArea) in between adding the two tool bars.
1,441,391
1,441,610
C++ Unit-Testing Framework for z/OS (IBM Mainframe)
Does anyone know of a C++ unit-testing framework (e.g. CppUnit, Google Test, etc.) that can be used to write tests on z/OS? I do most of my development on Windows using the Dignus C++ compiler, which you can use as a cross-compiler and generate object code to run on z/OS. I tried writing a sample test using Google Tes...
Try CPP Unit Lite (by CppUnit's author). It uses fairly straightforward C++ code, there's a good chance it'll work on z/OS's compiler.
1,441,423
1,441,439
Change repeat key threshold c++
I'm building a c++ tetris game (not c++ .Net). I feel my controls are weird. I want to make it so that when user presses one of the arrow keys, about 10ms of holding it down will start the repeat function windows has. It is set to about 500ms by default, and it is too laggy for my game. How can I set the speed at which...
Typically what you would do for this is instead of reacting to the WM_CHAR message that is subject to the normal key repeat settings, you would look for WM_KEYDOWN and WM_KEYUP, and take action based on a timer that you've got running. If you set the timer to fire every 50 ms for example, then you can repeat every 50 m...
1,441,510
1,441,516
directory structures C++
C:\Projects\Logs\RTC\MNH\Debug C:\Projects\Logs\FF Is there an expression/string that would say go back until you find "Logs" and open it? (assuming you were always below it) The same executable is run out of "Debug", "MNH" or "FF" at different times, the executable always should save it's log files into "Logs". Wha...
It sounds like you're asking about a relative path. If the working directory is C:\Projects\Logs\RTC\MNH\Debug\, the path ..\..\..\file represents a file in the Logs directory. If you might be in either C:\Projects\Logs\RTC\MNH\ or C:\Projects\Logs\RTC\MNH\Debug\, then no single expression will get you back to Logs fro...
1,441,885
1,443,309
Obtaining a pointer to Lua object instance in C++
I am using Luabind to expose a base class from C++ to Lua from which I can derive classes in Lua. This part works correctly and I am able to call C++ methods from my derived class in Lua. Now what I want to do is obtain a pointer to the Lua-based instance in my C++ program. C++ -> Binding class Enemy { private: std::...
If in Lua you do zombie = Zombie('example zombie', 1) then you can get the value of the zombie like this: object_cast<Enemy*>(globals(L)["zombie"]); (object_cast and globals are members of the luabind namespace, L is your Lua state) This assumes you know the names of the variables you create in Lua. You can always ...
1,441,904
1,441,924
Building command line applications
How can I move away from (in c++) the annoying menus like: (a) Do something (b) Do something else (c) Do that 3rd thing (x) exit Basically I want to be able to run the program then do something like "calc 32 / 5" or "open data.csv", where obviously I would have written the code for "calc" and "open". Just a shove in th...
You should pick up The C++ Programming Language, which is the book on C++ (there are others, but this one is great). It has an example program, spread over a few chapters, on tokenizing, parsing arguments, and making a calculator.
1,441,947
1,441,970
dynamic code compilation
I'm working on a program that renders iterated fractal systems. I wanted to add the functionality where someone could define their own iteration process, and compile that code so that it would run efficiently. I currently don't know how to do this and would like tips on what to read to learn how to do this. The main pr...
Some CPU emulators treat the machine code as if it was byte code and they do a JIT compile, almost as if it was Java. This is very efficient, but it means that the developers need to write a version of the compiler for each CPU their emulator runs on and for each CPU emulated. That usually means it only works on x86 an...
1,442,154
1,442,171
Can I add manifest file to someone else's exe?
I have some EXEs for which I do not have code. Can I still add manifest files? Also, according to my understanding of the topic, for a program to be Vista compliant, it should not write to any secured locations like HKLM, Program Files etc. For registry we can use HKCU, but about the files that are getting created in P...
You should be able to create a manifest file without source code. It it OK to require administrative privileges for installation or updates, so you can put the EXEs and DLLs (and supporting files) in Program Files. It is not OK to require administrative privileges for regular usage, so you should put data files and set...