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 |
|---|---|---|---|---|
3,564,871 | 3,564,982 | Difference between double comparisons in gtest (C++) and nunit (C#) | I have done porting of a c++ project with gtest tests to a c# project having an nunit test. Now I encounter problems with floating point precision.
in the nunit test I have being not ok (red)
Assert.AreEqual(0.7, 7 * 0.1);
in the gtest test I have:
ASSERT_DOUBLE_EQ(0.7, 7 * 0.1);
which is ok (green)
The question now... | Alternatively you can add a third parameter, which is the maximum difference between the two values, as you can read here.
public static void AreEqual (
double expected,
double actual,
double delta
)
Verifies that two specified doubles
are equal, or within the specified
accuracy of each other. The ass... |
3,564,948 | 3,565,010 | TFTP source code examples | Could someone point me to the source code for an ideally multi-threaded C++ TFTP application. Even better if it's written using boost asio.
Just wanting to get an idea of how to structure a multi-threaded c++ network app with UDP rather than TCP.
I'll choose the answer based on how readable the code is and being in C+... | Open TFTP Server Not purely C++ but a combination of C and C++
|
3,564,985 | 3,565,855 | returning std::string/std::list from dll | Short question.
I just got a dll I'm supposed to interface with.
Dll uses crt from msvcr90D.dll (notice D), and returns std::strings, std::lists, and boost::shared_ptr. Operator new/delete is not overloaded anywhere.
I assume crt mixup (msvcr90.dll in release build, or if one of components is rebuilt with newer crt, et... | The main thing to keep in mind is that dlls contain code and not memory. Memory allocated belongs to the process(1). When you instantiate an object in your process, you invoke the constructor code. During that object's lifetime you will invoke other pieces of code(methods) to work on that object's memory. Then when the... |
3,565,316 | 3,565,453 | Multidimensional array of object in C++ , I can not initialize it! | Rookie C++ Programmer here again
I'm using VC++ VS2008 and making an attempt at creating an array of arrays. All objects I wish to store I want to put on the heap.
In the arrays it's all just pointers.
Here's some code:
Grid.h
#include "Tile.h"
class Grid
{
public:
Tile* grid_ptr[8][8];
...
...
};
Grid.cpp
... | You don't want to create a Tile::Tile (a constructor), you want to create a Tile (an object) - change new Tile::Tile to new Tile.
Besides there is a leak. Remove this:
Grid::grid_ptr[i][0] = new Tile::Tile(10,10);
// EDIT
Probably you were confused with dynamic arrays (the one we use when dimensions are unknown). Your... |
3,565,368 | 3,565,374 | Ternary operator ?: vs if...else | In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code?
| Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.
|
3,565,388 | 3,565,507 | C++ Void non-pointer | I was wondering, why can't there be a void data type that is not a pointer?
Surely you could get past the whole determined size thing by having
void4
void8
void32
And then only being allowed to 'cast' a void data type to another class if its size is equal or under to the classes size.
Is there something that I'm missi... | In a strongly typed language, all data has a type, so there is no concept of "void" as a datatype. In C and C++, it's meanings are either "no data" (as a return value), or "data whose type you don't know" (as a pointer target).
You are proposing an in-between state of "data whose type you don't know but whose size you ... |
3,565,608 | 3,565,644 | How do I reference a 32 bit DLL in a 64 bit project? | I've got a C# 2.0 project which is set to target 'Any Cpu', however it is referencing a C++ project that's building a 32 bit dll.
When I try to run my program on a 64bit machine I get the following error:
System.BadImageFormatException was
unhandled Message: Could not load file
or assembly TreeTMHook,
Version=1.... | You'll need to build your .NET project as 32bit (x86 target) if you want it to correctly load a 32-bit DLL on a 64bit machine.
RE: Update:
If you want to keep your project as "Any CPU", you'll need a 32bit and a 64bit version of the DLL, and make sure the appropriate version is distributed with your app. If you can't b... |
3,565,970 | 3,566,136 | Qt Application Blocking System Shutdown | I have a Qt 4.6.2 application, running on a Windows XP SP2 x64 system.
When I press the physical power/shutdown button on the system, when my application is running nothing will happen, the app will not close and the system does not Shutdown.
If I go to start menu and click shutdown, then my application will close but ... | You need to reimplement QCoreApplication::winEventFilter in your QCoreApplication / QApplication derived class, and handle the WM_QUERYENDSESSION message there.
I'm not sure whether WM_QUERYENDSESSION will be delivered to your application or whether it's a broadcast system message (and I don't have a Windows machine ha... |
3,566,018 | 3,566,074 | Cannot open include file 'afxres.h' in VC2010 Express | I'm trying to compile an old project using VS express 2010 but I get this error:
fatal error RC1015: cannot open include file 'afxres.h'. from this code
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
I have install... | This header is a part of the MFC Library. VS Express edition doesn't contain MFC. If your project doesn't use MFC you can safely replace afxres.h with windows.h in your terrain2.rc.
|
3,566,264 | 3,566,311 | How to return a 2 dimensional vector? | I have a function that creates a 2D vector
void generate(int n)
{
vector< vector<int> > V (n, vector<int>(1 << n , 0 ));
.......
}//n is used to determine the size of vector
Now, I need to return the created vector to use it in another function .If I did
return V ;
it will be wrong because V is a local variab... | You can return V with no issues - it will return a copy of the local variable. Issues only arise when you return a reference or pointer to a variable with local scope; when the function ends, the local variable falls out of scope and is destroyed and the reference/pointer is no longer valid.
Alternatively, you can acce... |
3,566,355 | 3,566,433 | Registration-Free COM Objects on Windows-7/64bit | I'm trying to get the Registration-Free Activation of COM Components: A Walkthrough sample from Microsoft to run on a windows 7 Professional / 64bit machine. I've downloaded the demo program MSDNRegFreeCOM.msi.
I have it building and running correctly on my XP-32 dev box using VS2008SP1. But when I copy working 32bit... | Windows 7 reads the internal manifest file first and the external manifest secondly. Windows XP does the other way around.
http://blogs.msdn.com/b/junfeng/archive/2009/05/11/internal-manifest-vs-external-manifest.aspx
Merging an external manifest into the internal manifest can be done by running (in a "Visual Studio 20... |
3,566,491 | 3,566,627 | Memory usage and minimizing | We have a fairly graphical intensive application that uses the FOX toolkit and OpenSceneGraph, and of course C++. I notice that after running the application for some time, it seems there is a memory leak. However when I minimize, a substantial amount of memory appears to be freed (as witnessed in the Windows Task Ma... | What you are seeing is simply memory caching. When you call free()/delete()/delete, most implementations won't actually return this memory to the OS. They will keep it to be returned in a much faster fashion the next time you request it. When your application is minimized, they will free this memory because you won't b... |
3,566,524 | 3,566,568 | question about compress header | from this site there is header "compress.h"
http://www.fredosaurus.com/notes-cpp/examples/compress/compress.html
i am using visual c++ 2010 and also boost library and am interested if there is similary header of compress.h?
thanks
| Yes the header given on that page.
The web page seems to describe code that the author provides and at first glance it is standard and should work in Visual Studio
|
3,566,799 | 3,566,881 | C++ downcast ( using dynamic_cast ) returns NULL? | Environment: Linux C++ / Qt 4x
I do not understand why the following downcast returns NULL? I pasted base and derived class below.
Thanks in advance for any tips or suggestions.
-Ed
void MainWindow::onRtledaEventHandler(fes::EventArgs eventArgs)
{
// This cast returns a NULL ?
fes::AtsCommandEventArgs* atsComma... | You are passing a fes::EventArgs object by-value, which means it is a fes::EventArgs object. If you want to preserve the original type of polymorphic objects, pass a pointer or (better) a reference to them:
void MainWindow::onRtledaEventHandler(fes::EventArgs& eventArgs) {
fes::AtsCommandEventArgs& atsCommandEventAr... |
3,566,857 | 3,566,912 | System header files redefining macros: how do I tell gcc to ignore? | I have some Motif code that also uses widgets from the Xmt widget set.
It include both "Xm/XmStrDefs.h" and "Xmt/ComboBox.h".
However, there are some macros that are defined in both files:
// XmStrDefs.h:
#define XmNarrowSize "arrowSize"
// ComboBox.h:
#define XmNarrowSize "arrowSize"
These are system header files th... |
How can I tell gcc that these headers are system headers?
Use the -isystem switch. See http://gcc.gnu.org/onlinedocs/cpp/System-Headers.html for detail.
gcc -isystem Xm -I <rest of the nonsystem includes> ...
|
3,566,893 | 3,576,908 | pointer to class template | Here is the compilable code and the problem is still there
#include <iostream>
#include <string>
template<typename A,typename B,typename C>
class Mesh{
public:
Mesh(){}
Mesh(std::string file){
A foo;
std::cout << file << endl;
}
};
template<typename A, typen... | The problem is with your copy in the Simulator constructor. This code should make things a bit more obvious.
This has nothing to do with templates.
#include <iostream>
struct Mesh{ Mesh() { std::cout << "M:" << this << " ";} };
struct Pipe{
Mesh mesh;
Pipe() { std::cout << "PX:" << &mesh << " "; }
Pipe(int fil... |
3,567,182 | 3,567,427 | C++ open window hello world | How can you write a C++ program to open a window like this one...
Is it possible or can apps only be ran from the command line?
I'm using the G++ compiler... Do I need something else like visual studio?
Can I do it just by writing code?
| Take a look at Qt which is a cross-platform framework that easily builds GUIs.
Then check out a Qt tutorial, do a google search. Here is one that will get you to "hello world"
Also, you might want to check out Code::Blocks as an IDE. It will use your already installed g++ compiler.
|
3,567,359 | 3,567,389 | testing for valid pointer in c++ | I wrote a little test to check for null pointer, I simplified it with int and 0, 1, instead of real classes, what I'm trying to test is something like this: return p ? 1 : 0;
which in real world would be return p ? p->callmethod() : 0;
bool TestTrueFalse();
void main()
{
int i = TestTrueFalse();
}
bool TestTrueFals... | *p = 0;
you probably meant
p = 0;
*p = 0 sets what the pointer points to, not the pointer
|
3,567,906 | 3,568,024 | global variables in C++ | In a C++ multi-threaded application with many classes, i am trying to find out what are the methods to define a global variable
C style, define it as global in any one source file, define it as extern in a header which is included in the classes that access this variable.
Write a Singleton class, which contains these ... | If the scope of your "global variable" can be narrowed down (which is typically the case - how many variables are truly global?) then you can make it a private static class member in the appropriate owning class. If your other classes need to see it (or less likely, update it), provide get/put accessors.
|
3,568,064 | 3,568,162 | Cannot create ADODB.Connection with complicated programming chain | Ok so this is a really complicated problem, I will try my best to explain.
We have a c++ application which communicates with Sql Connection like so:
CoCreateInstance(_T("ADODB.Connection"))
This works fine.
We recently made all of our backend code into a Com Object. If I write a Vb program to load our Com Object and d... | It is telling you that it cannot find the ProgId in the registry. That's not very healthy, it is a pretty standard component on any Windows install. Verify this, fire up regedit.exe and navigate to HKLM\Software\Classes\ADODB.Connection
If that is missing then you need to install the dbase providers on that machine. ... |
3,568,069 | 3,568,155 | Is it safe to cast an int to void pointer and back to int again? | In C and/or C++: is it safe to cast an int to void pointer and back to int again?
Based on the question "C++: Is it safe to cast pointer to int and later back to pointer again?".
| In most modern-day commonplace machines, probably.
However, I'd bet that there is some obscure compiler or configuration (say, a 16-bit addressed machine that uses 32-bit integer arithmetic) where that is not the case.
A uintptr_t is guaranteed to hold both, though, so use that type if you want to.
|
3,568,166 | 3,568,202 | Would it make sense to have a 'constify' operation in C++? | Would it make sense to have a "constify" operation in C/C++ that makes a variable const?
Here is an example where it could be useful, where obviously we don't want to declare it const yet in the first line:
std::vector<int> v;
v.push_back(5);
constify v; // now it's const
Currently, without such a possibility, you'd h... | Frankly, I find it less confusing if a variable is either const or not, than if this can change.
To elaborate a bit on this: The reason you usually want to do this is because you cannot initialize a const variable the way you want to. std::vector is a good example of this. Well, for once, the next standard introduces... |
3,568,387 | 3,568,757 | Compiler error in VC++2010 (clean in 2008!), "ambiguous call to overloaded function" | I'm hitting a compile error in VS2010 with code that compiles cleanly in VS2008.
Here's my error, from the Output Window, with all of its verbosity:
...\elementimpl.h(49): error C2668: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string' : ambiguous call to overloaded function
with
[
_Elem=char,
... | The problem is, that VS2010 added move constructors and your implementation falls directly into this hole.
Previously there was only one constructor, the const char* one, which was available to the std::string constructor. Now there is the move constructor, too.
I really think a design relying on implicit conversions i... |
3,568,503 | 3,568,556 | Extra brace brackets in C++ code | Sometimes you run into code that has extra brace brackets, that have nothing to do with scope, only are for readability and avoiding mistakes.
For example:
GetMutexLock( handle ) ;
{
// brace brackets "scope" the lock,
// must close block / remember
// to release the handle.
// similar to C#'s lock construct
}... | The braces themselves are fine, all they do is limit scope and you won't slow anything down. It can be seen as cleaner. (Always prefer clean code over fast code, if it's cleaner, don't worry about the speed until you profile.)
But with respect to resources it's bad practice because you've put yourself in a position to... |
3,568,546 | 4,594,841 | Colorization and Palette Best-Fit Algorithms | Been poking around google and haven't found any like what I'm after. so what is it I'm after? well two things:
firstly I'm looking for an
algorithm/pseudo-code/white-papers
to determine a best-fit color for a
give r,g,b tuple from and array of
256 RGB tuples.
Secondly, I'm looking for an
algorithm/pseudo-code/white-p... | See http://en.wikipedia.org/wiki/Color_difference for how to calculate distances between colors so that human eye sensitivity is taken into account.
|
3,569,001 | 3,570,670 | c++ winsock code does not work in its original solution/project in visual studio 2010 | I am not 100% sure if I shall become insane...
As mentioned in many many other posts, I am writing this Connection class which stats up winsock, creates some sockets, binds them and let´s you send and receive some data...
I made this within my Server-project...
But , everytime i wanted to test the connection part of th... | Ok... I am not sure, why this problem appeared...
But the solution was to create a new solution and insert the "old" files...
finally it works :)...
I hope it wasn´t the windows firewall, but I did check this...
|
3,569,005 | 3,569,028 | Problem with iostream | I m using MinGW for running g++ compiler on windows. Whenever I run the following code, it the compiler gives strange results.
Code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int n;
string a;
cin>>n;
getline(cin,a);
cout<<a;
return 0;
}
No problem occurs when I ... | The problem is in your code. In a nutshell, the newline you type to commit the number for n is still stored in the input buffer as it is not numerical input, so is not consumed by n. The getline function then absorbs the newline and completes.
|
3,569,424 | 3,569,581 | How to do a double-chunk add with no undefined behaviour? | EDIT Public health warning - this question includes a false assumption about undefined behaviour. See accepted answer.
After a reading recent blog post, I've been thinking a lot about the practicality of avoiding all standards-undefined assumptions in C and C++ code. Here is a snippet cut out of C++, to do an unsigned ... | From the C++ 1998 standard, 3.9.1(4): "Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer." Note that "integer", here, refers to any integer type rather than just int.
Therefore, assuming that ... |
3,569,643 | 3,584,383 | abort() is not __declspec(noreturn) in VS2010 | In my copy of VS2010, stdlib.h contains (lines 353-355)
_CRTIMP __declspec(noreturn) void __cdecl exit(_In_ int _Code);
_CRTIMP __declspec(noreturn) void __cdecl _exit(_In_ int _Code);
_CRTIMP void __cdecl abort(void);
I find it strange that there's no noreturn annotation on abort(). Does anyone know a reason for thi... | I think this is definitely wrong because regardless of what the std mandates, the abort() implementation shipped with Visual Studio will never return from abort. You cannot do anything in the signal handler for SIGABRT that will prevent _exit(3) being called at the end of the abort() implementation of Visual Studio (I'... |
3,569,856 | 3,569,868 | Const pointer in a class object-oriented bug | I have a simple example below that does not compile. i get the following warrning about const
Error message:
error C2662: 'Cfoo::GetNum' : cannot convert 'this' pointer from 'const Cfoo' to 'Cfoo &' Conversion loses qualifiers
class Cfoo
{
public:
bool RunMe( const Cfoo * bar ) {
int i = bar->... | GetNum must promise it does not change the value of the object by making it a const member function
class Cfoo
{
public:
bool RunMe( const Cfoo * bar ) {
int i = bar->GetNum() ;
}
int GetNum() const { // !!!
return 7;
}
};
|
3,569,859 | 3,569,885 | Questions regarding "warning C4312: 'type cast'" | This is the code I have:
HWND WebformCreate(HWND hParent, UINT id)
{
return CreateWindowEx(0, WEBFORM_CLASS, _T("about:blank"),
WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, 0, 0, 100, 100, hParent,
(HMENU)id, GetModuleHandle(NULL), 0);
}
This is the warning I get:
warning C4312: 'type cast' : conversio... | You're casting a 32bit UINT to a 64bit pointer. That's suicide - you're trying to point to something but forgot half it's location! You absolutely MUST take a UINT_PTR. When you cast a pointer to an int, the behaviour is only OK if the int has the same size as the pointer. Else, it's the end of your application's runti... |
3,569,877 | 3,569,969 | Is it possible to load a function into some allocated memory and run it from there? | I'm messing around with some interprocess communication stuff and I am curious if it's possible to copy a function into some shared memory and run it from there from either process.
Something like:
memcpy(shared_memory_address, &func, &func + sizeof(func));
I realize you can't take the size of the function but that wa... | Theoretically, as functions are just sequence of byte code somewhere in the memory, you could copy the memory block of the function and call (jump into) it. Though c++ Abstracts that possibility away, as you noticed, we cannot actually know the size of function (although we can get pointer to it).
Still, there's librar... |
3,570,024 | 3,570,083 | Compiling a project (VS 2008) with the /p argument (preprocess to a file) doesn't compile | I have a project in C++ that I would like to view the preprocessor output to see what some #defines and macros would look like. I tried the /p switch to turn on the preprocess to a file option to the compiler (it turns off full compilation and only runs the preprocessor) but my project now refuses to compile and shows... | If you run cl.exe on its own then you would need to supply all the same parameters as the IDE does when building, otherwise it can't find all the include paths and preprocessor macros. However, there is another way to do this. In the project file, select the .cpp file you want, and choose Properties > C++ > Preproces... |
3,570,119 | 3,570,203 | Is this considered memory leak? | The general rule, only objects allocated in the free store can cause memory leaks.
But objects created in the stack doesn't.
Here is my doubt,
int main()
{
myclass x;
...
throw;
...
}
If throw is not handled, it calls, terminate(), which in turn calls abort() and crashes the applicat... | In a hosted environment (e.g. your typical Unix / Windows / Mac OS X, even DOS, machine) when the application terminates all the memory it occupied is automatically reclaimed by the operating system. Therefore, it doesn't make sense to worry about such memory leaks.
In some cases, before an application terminates, you... |
3,570,222 | 3,817,089 | Comparison of Boost StateCharts vs. Samek's "Quantum Statecharts" | I've had heavy exposure to Miro Samek's "Quantum Hierarchical State Machine," but I'd like to know how it compares to Boost StateCharts - as told by someone who has worked with both. Any takers?
| I know them both, although at different detail levels. But we can start with the differences I've came across, maybe there are more :-) .
Scope
First, the Quantum Platform provides a complete execution framework for UML state machines, whereas boost::statechart only helps the state machine implementations. As such, boo... |
3,570,265 | 3,570,326 | Baffling gcc complaint about usage of Qt4 setValidator | We're stumped as to why gcc complains about this line in our app:
doubleFrom->setValidator(new QDoubleValidator(doubleFrom));
with these complaints:
error: expected type-specifier before 'QDoubleValidator'
error: expected `)' before 'QDoubleValidator'
error: no matching function for call to 'QLineEdit::setValidator(in... | This is really basic and obvious, I know, but did you #include <QDoubleValidator>?
"Expected type-specifier before <identifier that should name a type>" almost always means that the type definition isn't visible.
|
3,570,355 | 3,570,430 | C++ -fvisibility=hidden -fvisibility-inlines-hidden | I have a question about the C++ visibility attribute. I have read http://gcc.gnu.org/wiki/Visibility and yet I dont quite understand how it works.
I want use the visibility to be hidden on some of my shared libraries I have. I believe this means that the symbols are hidden ?
How are you meant to link the shared library... | -fvisibility=hidden makes all your symbols hidden by default.
What you then have to do, is choose which functions you want to be visible to users linking against your library and make them visible by marking them with a visible attribute.
E.g.
void __attribute__((visibility("default"))) Exported()
{
// ...
}
|
3,570,617 | 3,570,686 | Using ASM when compiling x64 C++ with MSVC10 | Due to MSVC10 not allowing the use of inline ASM instructions when targeting x64 architecture, I'm looking for any ways to get around such restrictions. I have learned from googling that writing and compiling separate ASM modules then linking against them and calling them from C++ is one way, however I have no idea how... | You can use a separate assembler program which will compile complete assembler source files into object files. So long as you follow the correct calling conventions you can provide prototypes for the functions for use in C++ link the C++ and ASM generated object files together.
I use yasm . It uses intel syntax, suppo... |
3,570,673 | 3,570,716 | use of rand() function to generate ascii values | int RandInt(int a, int b){
return (rand()%b+a);
}
I want to generate the random character values so i call it like this
char asciiValue = RandInt(65, 90);
but my output is not quite what i expect... am i doing something wrong?
--edit put in wrong values for randint call, my bad
| RandInt(90, 90) will return an integer between 90 and 179. The value 90 represents a 'Z' and you can have a value up from there.
What range are you tring to get?
Capital letters would be RandInt(65, 26). Is this what you expect?
|
3,570,892 | 3,571,028 | Binary parser or serialization? | I want to store a graph of different objects for a game, their classes may or may not be related, they may or may not contain vectors of simple structures.
I want parsing operation to be fast, data can be pretty big.
Adding new things should not be hard, and it should not break backward compatibility.
Smaller file siz... | Point by point:
Fast Parsing: binary (since you don't necessarily have to "parse", you can just deserialize)
Adding New Things: text
Smaller: text (even if gzipped text is larger than binary, it won't be much larger).
Readability: text
So that's three votes for text, one point for binary. Personally, I'd go with tex... |
3,571,156 | 3,573,283 | Why doesn't this Boost ASIO code work with this python client? | This code is identical to the original udp async echo server, but with a different socket.
The response is transmitted and showing in wireshark, but then an ICMP Port Unreachable error is sent back to the server. I'm trying to understand why because everything looks correct.
You can copy this code directly into a sour... | Here we go. I'm answering my own question again. The problem relates to my python code
which was a sample I grabbed from someone else.
This version works a whole heap better and reads the result correctly. And, is using the correct API sendto recvfrom which is what you would normally use with udp packets.
#!/usr/bin... |
3,571,222 | 3,581,746 | how to use Savitzky-Golay smooth coefficient to calculate derivatives | Savitzky-Golay smoothing filter can be used to calculate the coefficients so as to calculate the smoothed y-values by applying the coefficients to the adjacent values. The smoothed curve looks great.
According to the papers, the coefficients can also be used to calculate the derivatives up to 5th order. The coefficient... | To calculate the derivatives using Savitzky-Golay smoothing filter, the polynomial coefficients computation has a parameter b, the value b[derivative] must be set to 1.0, the array be will be used in the LU decomposition call.
The key to get derivatives right is to understand the polynomial formula: Y = a0 + a1 * z + a... |
3,571,250 | 3,571,256 | wWinmain, Unicode, and Mingw | I am working on learning the windows API and am using mingw as my compiler with Code::Blocks as my IDE. I have run into an issue with using the wWinMain function. I used the program located here link text. It compiles fine on VSC++ 2008 express but when using mingw i get the "undefined reference to WinMain@16" error... | Use the plain (non unicode) WinMain function, and then get your unicode command line using GetCommandLineW. MinGW doesn't know about wWinMain.
You are probably going to find working on MinGW difficult; last time I used it it did not support most of the wchar_t components of the C++ standard library (i.e. std::wifstream... |
3,571,300 | 3,571,766 | incorporate .so into another .so without dependency? | i have a c program that relies on a second library whose compilation i can control. i want to be able to compile my program into a shared object library without it linking to the second library. in other words i want a single monolithic shared object library at the end. how can i do this?
if i separately compile the se... | You need to compile your second library as a .a (static library) and statically link that into your c program.
Static linking is when object files are linked at compile time and are part of the final binary, the resulting executable can be executed with no dependencies..
Shared libraries (.so) are linked at run time a... |
3,571,496 | 3,571,626 | Objective-C/C++ constants | EDIT: My example might have created some confusion. I have changed the example below to reflect what I want to achieve. Hope this is more clear.
I am trying to define a constant in my objective-c code. I am using the standard #define to do this. Eg:
#define bluh "a"
I would like to define another constant like th... | I don't know objective C. In C++, adjacent string literals are concatenated, so it's adequate to use:
#define blah bluh "b"
BTW / it's standard practice to use uppercase for preprocessor defines wherever possible, and for no other purpose, minimising the chance of unexpected substitutions.
|
3,571,624 | 3,571,740 | Free C++ profiler for Windows | What free profilers are there fore Windows 7 that are compatible with vs2010?
| I've never had to look for one (because I use MinGW and it has a profiler for free), and I've never used this one before, so I don't know if it has all the features you're looking for, but try this anyway?
Very Sleepy Profiler
Xperf from Windows Performance Analysis Tools
Hope this helps!
|
3,571,704 | 3,571,746 | C++ template member variable in templatized class has incomplete type | I have code similar to the following in a header file:
template<class A>
class List {
private:
QVector<A> _list;
};
where QVector is the standard QT container.
When I try to make a variable of type List as a member variable in another header file like this:
class Model {
private:
List<int *> the_list;
};... | Make sure you have #included the header file for QVector before your declaration of class List { }. If you omit it then QVector is an undefined type but because List is a templated class the compiler doesn't omit an error message until you instantiate List for the first time.
#include <QVector>
template<class A>
class... |
3,571,756 | 3,578,904 | SDL C++ Application not doing anything when built using Visual Studio 2010 | I've just started using C++ again after using solely VB for a year and I wanted to try my hand at cross platform development. So I started learning to use SDL (which is very very easy thankfully) to create simple graphics driven games like Pong and Tetris. I am compiling the code with Microsoft VisualStudio 2010 Enterp... | Okay I figured it out, stupid me forgot to include the true-type font file I was using. I found this out by writing to a log file every major step. After I noticed the app crashing with font_load() began... 'timestamp' written as the last thing in the log file, it was obvious.
|
3,571,771 | 3,571,776 | Are all functions in the c++ standard library required have external linkage? | So I've got an app which compiles fine on windows, linux and a few variations of unix. I recently decided to port it to OSX when I ran into a snag.
I have a template which looks like this:
template<int (&F)(int)>
int safe_ctype(unsigned char c) { return F(c); }
the idea being to prevent sign extension from crashing ce... | C++03 §17.4.2.2/1 says:
Entities in the C++ Standard Library have external linkage.
The same is true in C: C99 §7.1.2/6 says:
Any declaration of a library function shall have external linkage.
|
3,571,879 | 3,571,929 | About Google's protobuf | I know it can be used to send/receive structured object from file,
but can it be used to send/receive sequences of structured object from a socket?
http://code.google.com/p/protobuf/
| Protocol Buffers is a structured data serialization (and de-serialization) framework. It is only concerned with encoding a selection of pre-defined data types into a data stream. What you do with that stream is up to you. To quote the wiki:
If you want to write multiple messages
to a single file or stream, it is up
... |
3,571,959 | 3,571,985 | What is meant by 'use of a function' | $3.6.1/3 states-
"The function main shall not be used
(3.2) within a program.".
The sample academically motivated program below uses the name 'main' in a couple of ways which I thought are legitimate. This is based on the assumption that 'usage of a function' is related to calling the function (directly/indirectly)... | C++03 §3.2/2 says:
An object or non-overloaded function is used if its name appears in a potentially-evaluated expression.
It goes on to list what constitutes use of other various types of entities; this is the important one here.
A friend declaration is not an expression.
When the function main() is converted to a... |
3,571,975 | 3,571,996 | C++ assignment operator - compiler generated or custom? | I have a medium complex C++ class which holds a set of data read from disc. It contains an eclectic mix of floats, ints and structures and is now in general use. During a major code review it was asked whether we have a custom assignment operator or we rely on the compiler generated version and if so, how do we know i... | It is well-known what the automatically-generated assignment operator will do - that's defined as part of the standard and a standards-compliant C++ compiler will always generate a correctly-behaving assignment operator (if it didn't, then it would not be a standards-compliant compiler).
You usually only need to write ... |
3,572,082 | 3,572,133 | c++ repaint part of window | i want to repaint part of the window not the whole thing. i have no idea how to. im using win32 please no mfc........
thanks in advance
// create rect structure
RECT rect2;
rect2.left=0;
rect2.top=0;
rect2.right=225;
rect2.bottom=300;
// calling invalidateRect when left mouse button is donw
case WM_LBUTTONDOWN:
Inv... | Pass the rectangle of the portion of window, which you want to re-paint, in InvalidateRect() method. Read here for details.
|
3,572,294 | 3,572,589 | C++/Qt Multiline strings; also, multiple queries | Two [hopefully] quick questions regarding C++/Qt. Is the following proper for writing a string on multiple lines?
QString strQuery;
strQuery="\
CREATE TABLE foo\
(bar integer primary key,\
baz varchar(20))";
I believe this is right, but in Qt Creator it doesn't highlight as though it... | I think that will be the right way:
QString strQuery;
strQuery="CREATE TABLE foo " \
"(bar integer primary key, " \
"baz varchar(20));";
// with this style `strQuery` will be single line, like "CREATE TABLE foo (bar integer primary key, baz varchar(20));"
QSqlQuery query;
QString strQuery;
strQuery... |
3,572,310 | 3,572,332 | A method which can only be invoked when referring to base class? C++ | Say I have an abstract class
class NecessaryDanger
{
public:
virtual void doSomethingDangerous() =0;
}
and a class that is derived from this class:
class DoesOtherStuff : public NecessaryDanger
{
//stuff
void otherMethod();
void doSomethingDangerous();
}
is there a way I can only allow access of d... | Sure. Just make it private in the derived class and public in the base.
Of course, if NecessaryDanger is a public base, then anyone can cast and call. You might want to make it a private base and use friend.
class DoesOtherStuff : private NecessaryDanger
{
//stuff
void otherMethod();
private:
void doSom... |
3,572,343 | 3,572,405 | How to obtain a value based on a certain probability | I have some functions which generate double, float, short, long random values. I have another function to which I pass the datatype and which should return a random value. Now I need to choose in that function the return value based on the passed datatype. For example, if I pass float, I need:
the probability that the ... | C++ random numbers have uniform distribution. If you need random variables of another distribution you need to base its mathematical formula on uniform distribution.
If you don't have a mathematical formula for your random variable you can do something like this:
int x = rand() % 10;
if (x < 7)
{
// return float
}
els... |
3,572,371 | 3,572,383 | Does this code check for endianess? | I heard in little endian, the LSB is at starting address and in Big endian MSB is at starting address. SO I wrote my code like this. If not why ?
void checkEndianess()
{
int i = 1;
char c = (char)i;
if(c)
cout<<"Little Endian"<<endl;
else
cout<<"Big Endian"<<endl;
}
| No, you're taking an int and are casting it to a char, which is a high-level concept (and will internally most likely be done in registers). That has nothing to do with endianness, which is a concept that mostly pertains to memory.
You're probably looking for this:
int i = 1;
char c = *(char *) &i;
if (c) {
cout <<... |
3,572,459 | 3,572,486 | How can I study and practices on C++ pointer? | I'm moving from C# to C++, one of priority topic for me is pointer. I'm reading some book and some blog post about pointer and I understand its basic concept. Now I want to learn about pointer by practicing it.
I try to search on google, unfortunately not thing found. Are there anything can help me study and practices ... | Just google for "learn C pointers". For example, you'll find stuff like http://computer.howstuffworks.com/c20.htm
Once you understand what a pointer is, what it does, and how it is managed, start using C++ smart pointers which take care of some of the grunt work for you.
|
3,572,610 | 3,572,643 | stack growth direction | So from my previous memmove question I would like to know how to find direction of stack growth.
void stackDirection(int* i)
{
int j;
if(&j>i)
cout<<"Stack is growing up \n"<<endl;
else
cout<<"Stack is growing down \n"<<endl;
}
int main()
{
int i=1;
stac... | The stack may not grow up or down.
Each stack frame can potentially be allocated at random points inside the heap.
This is actually done in several OS to try and prevent stack smashing by malicious code.
The concept of a stack growing towards the heap is just an easy way to teach the concept of a stack (and of course e... |
3,572,753 | 3,572,814 | difference between c's expression and c++'s expression | int main()
{
int i=3;
(++i)++;
printf("%d",i);
}
This programs works with g++ compiler but not gcc.
If i write i++++ or ++i++ it doesn't work in cpp also.
I think there is difference between c-expression and c++-expression.
Can somebody explain about L-value and R-value ?
| Edit: This answer is incorrect for the updated question, it applies to the question as originally stated.
(i++)++ shouldn't work with either gcc or g++, whether or not they are parsing the file as C or C++ in both languages postfix increment requires an lvalue as an operand and the result is an rvalue.
(Note that rval... |
3,572,788 | 3,572,839 | C++: Where to write the code documentation: in .cpp or in .hpp files? | Where is it customary to write the in-code documentation of classes and methods?
Do you write such doc-blocks above the corresponding class/method in the header (.hpp) file, or within the source (.cpp) file?
Is there a widely respected convention for such things? Do most C++ projects do it one way rather than the... | Both:
Describe the API design and usage in the header: that's your public interface for clients.
Describe the implementation alternatives / issues and decisions in the implementation: that's for yourself - later - and other maintainers/enhancers, even someone reviewing the design as input to some next-gen system years... |
3,572,874 | 3,572,962 | How Can I call a C++ Win32 DLL from another C++ win32 Console Application | What is my main concern is , I am able to write a C++ dll using VC++ . Now the dll is present in the Debug folder.
How can I use my DLL in other C++ Console Application. How to add reference or link the DLL to the application.
Another point, While creating a DLL , The VC++ wizard gives me thre option:
An Empty DLL pro... | Not completely sure what you questions are but:
It doesn't really matter which option you use it is just a matter of what the wizard does for you; if you use the third option then the wizard creates a bit in your header file that looks like this:
#ifdef TEST_EXPORTS
#define TEST_API __declspec(dllexport)
#else
#define ... |
3,572,974 | 3,573,256 | Error building legacy code with VS 2005 | Trying to build a legacy code in VS2005 and get errors in VC header files.
d:\Compilers\Microsoft Visual Studio 8\VC\include\xutility(2096) : error C2065: '_Sb' : undeclared identifier
d:\Compilers\Microsoft Visual Studio 8\VC\include\xutility(2176) : see reference to class template instantiation 'std::istreambuf_i... | You may find that running the pre-process phase on one of the files might show if any macros are being expanded that conflict with vector or _Strbuf. See my post on how to do this:
Compiling a project (VS 2008) with the /p argument (preprocess to a file) doesn't compile
|
3,573,301 | 3,573,337 | how to allow a process created by another process, use a part of memory of the creator process? | I got two console processes that second one is created by first one using the API below:
BOOL WINAPI CreateProcess(
__in_opt LPCTSTR lpApplicationName,
__inout_opt LPTSTR lpCommandLine,
__in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in ... | You can access this memory using ReadProcessMemory/WriteProcessMemory API. Another process needs to know memory address and handle of the process to access its memory.
|
3,573,314 | 3,573,455 | question about link and include of different vers of a lib | Is it a problem if I have an executable and a library use different
versions of another library.
Example:
If I have an executable: A.exe, and it basically wraps and depends on
a static library A.lib
Both A.exe and A.lib need another library B.lib
If I have a situation like this:
The A.lib library includes B.lib ... | If the same functions exist in both B1.Lib and B2.Lib and both are linked to A.exe you may end up with a problem. Basically if B1::fn returns different results to B2::fn and A.Lib relies on the B1 results and A.exe relies on the B2 results you have a MAJOR problem. The linker will just link to the first implementatio... |
3,573,753 | 3,574,101 | usage of clutter for game development | I'm a relatively new developer, and I'm looking to learn C++. I've had experience coding in java, javascript, actionscript, and python, but I want something fast enough to do some high performance 2D and 3D games.
When I eventually learn the basics (control structures, classes, etc) I'd like to develop a 2D game. I've ... | I must admit I've never heard of Clutter before, probably because it's not a Windows library and the majority of games developers work on Windows platforms. Similarly, most game developers (even indie/hobbyist ones) are not considering Cairo, or Openframeworks either. More common by far would be the use of SDL, althoug... |
3,573,768 | 3,573,799 | Is there "magic" in the STL? | Let me start with explaining what I mean with "magic". I will use two examples from Java:
Every class inherits (directly or indirectly) the Object class.
Operator overloading is not supported by Java but the + operator is defined for String objects.
This means that it is impossible to make an implementation of the Ob... | in other words, has anything been done to the compiler to allow for a 'special case' the STL needed to work?
No.
It was all implemented as 'pure' C++ code, using the magic of templates.
There has been some work done to compilers to improve the STL (I'm thinking about various optimisations) but otherwise, no, you could... |
3,573,800 | 3,573,929 | String tokenizer for CPP String? | I want to use string Tokenizer for CPP string but all I could find was for Char*.
Is there anything similar for CPP string?
| What do you mean by "token"? If it's something separated by any whitespace, the string streams is what you want:
std::istringstream iss("blah wrxgl bxrcy")
for(;;) {
std::string token;
if(!(iss>>token)) break;
process(token);
}
if(!iss.eof()) report_error();
Alternatively, if your looking for a a certain singl... |
3,574,019 | 3,574,160 | enable_shared_from_this and objects on stack | Is there a way to prevent shared_from_this() call for a stack-allocated object ?
The enable_shared_from_this<> in the base classes list is a strong indicator for class user, but is there a way to enforce the correct usage ?
Example code:
class C : public enable_shared_from_this<C>
{
public:
shared_ptr<C> method() { ... | So to protect against this problem you can make your constructors private and only provide creation functions that return shared_ptr - this way the object can't be allocated on the stack, like this:
class C : public enable_shared_from_this<C>
{
public:
static shared_ptr<C> create() { return shared_ptr<C>(new C() ); }... |
3,574,040 | 3,574,086 | C++: Can a struct inherit from a class? | I am looking at the implementation of an API that I am using.
I noticed that a struct is inheriting from a class and I paused to ponder on it...
First, I didn't see in the C++ manual I studied with that a struct could inherit from another struct:
struct A {};
struct B : public A {};
I guess that in such a case, stru... | Yes, struct can inherit from class in C++.
In C++, classes and struct are the same except for their default behaviour with regards to inheritance and access levels of members.
C++ class
Default Inheritance = private
Default Access Level for Member Variables and Functions = private
C++ struct
Default Inheritance = pu... |
3,574,147 | 3,574,418 | Qt heap memory corruption | I'm writing a Qt 4.6 application (without the qt designer) and when I close the program I get this error from Visual Studio:
Windows has triggered a breakpoint in
Test.exe.
This may be due to a corruption of the
heap, which indicates a bug in
Test.exe or any of the DLLs it has
loaded.
This may also be due to t... | In ExtWiiMote.h you declared
QLabel* dots[3][3];
and in the ExtWiiMote.cpp you use dots[3][0]....
Fix dots array size and probably you'll be fine.
|
3,574,208 | 3,574,332 | how do i use the c++ dll in c# | i like import c++ dll in my c# application how can i Do this?, what is concept i need to use for this?
| suppose this DLL that compile with MinGW.
in C-sharp you can follow this code:
using System.Runtime.InteropServices;
using System;
class call_dll {
[StructLayout(LayoutKind.Sequential, Pack=1)]
private struct STRUCT_DLL {
public Int32 count_int;
public IntPtr ints;
}
[DllImport("mingw_dll.dll")]
... |
3,574,569 | 3,575,225 | How to find the neighbours of a node in Lemon | In the Lemon C++ Graph Library, given a node in an undirected graph say, how does one find other nodes that are edge connected?
| I'll have a go at this even though I'm rusty with C++ and haven't used Lemon before:
for (ListDigraph::OutArcIt arcIt(graph, node); arcIt != INVALID; ++arcIt) {
Arc arc(*arcIt); // Lemon iterators are supposed to be convertible to items
// without operator*, so arc(a) might work too.
Node... |
3,574,680 | 3,574,713 | Sort based on multiple things in C++ | struct Record
{
char Surname[20];
char Initial;
unsigned short int Gender; //0 = male | 1 = female
unsigned short int Age;
};
Record X[100];
How can I use Quicksort to sort the values into increasing age, with females before males and surnames in alphabetical order? I've got a:
bool CompareData(const i... | bool CompareData(const int& A, const int& B)
{
return (Records[A].Age < Records[B].Age) ||
((Records[A].Age == Records[B].Age) && (Records[A].Gender > Records[B].Gender)) ||
((Records[A].Age == Records[B].Age) && (Records[A].Gender == Records[B].Gender) &&
(strcmp(Records[A].Sur... |
3,574,823 | 3,575,334 | How to get directories,subdirectories, files creation date & time from FTP remote Server in C++? | How to get directories,subdirectories, files creation date & time from FTP remote Server in C++ ?
I want to create a FTP client in C++
| CIt doesn't matter the language, Once you are connected to the ftp server, just send the commands following the FTP protocol..
You should check the File Transfer Protocol RFC
That is if you want to do an ftp client from scratch. You can use libraries for doing so.
The commands you need, could be LIST command. But It is... |
3,574,840 | 3,575,249 | Does reinterpret_cast store a copy of object pointer? | when a reinterpret_cast is applied to a class object, it returns a LONG_PTR. is it some sort of handle to a temporary object pointer stored somewhere in memory?
| The question's not so well worded. I can't think of any manner of object for which reinterpret_cast<LONG_PTR>(object) would work, assuming LONG_PTR is some pointer type (it's not Standard C++), and object is a class instance (the C++ Standard considers variables of built in types to be objects too - that could work).
... |
3,574,853 | 3,580,673 | debugging a process spawned with CreateProcess in Visual Studio | I've created a Windows/C++/WTL application that spawns a child process. The two processes communicate via anonymous pipes.
I'd like to be able to debug the child process.
Since both parent and child projects are in the same solution in Visual Studio 2008, is there any way to tell VS2008 that I'd like the debugger to... | You could put a global named mutex around your CreateProcess call, and then try to grab the mutex in the child process. If you then put a breakpoint on the CreateProcess call, you should have time to attach to the child before it does anything substantial.
Note that you would miss anything that happens before main in t... |
3,574,972 | 3,575,220 | QString, remove labels and content? | message.Text() is a QString.
I want to remove some text.
The text can be:
Normal: "This is a text"
With a label: "<label1>something</label1>This is a text"
First, I find if the text has the label:
!message.Text().contains("<label1>", Qt::CaseInsensitive))
So, if it has, I want to remove the first part, to have a nor... | Try the following:
#include <iostream>
using std::cout; using std::endl;
#include <QString>
int main()
{
QString message = "<label1>something</label1>This is a test";
const QString labelClose = "</label1>";
const int labelCloseSize = labelClose.size();
cout << "message: " << qPrintable(message) << endl;
co... |
3,575,117 | 3,575,177 | Is there a native/reliable alternative for boost::shared_ptr in VC++? | My company doesn't allow the use of boost (for many stupid reasons, but that's off-topic).
I feel very frustrated having to use raw pointers when I'm used to shared_ptr, weak_ptr and scoped_ptr for personal development.
We're working exclusively with Microsoft compilers (Visual Studio 2010) and I wonder if there was an... | With VC10 just use the shared_ptr, weak_ptr and unique_ptr implementations it already provides. All you have to do is to include <memory>.
|
3,575,212 | 3,575,255 | What does mean this C++ code: "void Foo() throw;"? | Question from the one interview.
Please explain what does this C++ code mean:
void Foo() throw;
| void Foo() throw;
This is a syntax error. The grammar for exception specification (C++98 §15.4) is:
exception-specification:
throw ( type-id-listopt )
Note that the parenthesis are required.
On the other hand,
void Foo() throw();
means the function Foo() will not throw any exceptions.
|
3,575,234 | 3,575,344 | reinterpret_cast cast cost | My understanding is that C++ reinterpret_cast and C pointer cast is a just
a compile-time functionality and that it has no performance cost at all.
Is this true?
| It's a good assumption to start with. However, the optimizer may be restricted in what it can assume in the presence of a reinterpret_cast<> or C pointer cast. Then, even though the cast itself has no associated instructions, the resulting code is slower.
For instance, if you cast an int to a pointer, the optimizer lik... |
3,575,367 | 3,575,645 | Prepared Statement with Select? Possible? | is it possible to use prepared statements with the SELECT command?
I wrote in C++ following code:
sqlite3_bind_int(this->ppGetStmt, 1, id);
int rc = sqlite3_step(this->ppGetStmt);
//sqlite3_result_int(this->ppGetStmt, &value);
sqlite3_reset(this->ppGetStmt);
The SQL statement looks like following SELECT value FROM t... | After each call to sqlite3_step() for which you receive a SQLITE_ROW return value, you use the column access functions to get your values out.
|
3,575,458 | 3,575,509 | Does new[] call default constructor in C++? | When I use new[] to create an array of my classes:
int count = 10;
A *arr = new A[count];
I see that it calls a default constructor of A count times. As a result arr has count initialized objects of type A.
But if I use the same thing to construct an int array:
int *arr2 = new int[count];
it is not initialized. All v... | See the accepted answer to a very similar question. When you use new[] each element is initialized by the default constructor except when the type is a built-in type. Built-in types are left unitialized by default.
To have built-in type array default-initialized use
new int[size]();
|
3,575,569 | 3,575,593 | Is there a way to jump into a specific part of code to debug? | Do I have to go over all the program using F11 and F10 . Can't I just mark where I want to go and start from there ?
| Put a breakpoint to the line of code you're interested in and just start the program. It will run until control passes that line for the first time and the debugger will pause the program at that line and let you debug it.
|
3,575,580 | 3,575,644 | Rationale behind static const (non-integral) member initialization syntax? | I know how to initialize a static member that's not an integer, but I'm wondering, what is the rationale behind the syntax for this? I'd like to be able to just put the value in the class, like you can with an integer member, a la:
class A {
static const int i = 3;
};
I realise this could mean more rebuilding if I c... | Because that is the class declaration. You don't have any object yet.
You need to actually define the value somewhere --- somewhere specific.
Since it is static it's actually taking up space somewhere. But, since the .H file which has that declaration can be #included in many source files, which one defines holds the... |
3,575,592 | 3,575,630 | What are near, far and huge pointers? | Can anyone explain to me these pointers with a suitable example ... and when these pointers are used?
| In the old days, according to the Turbo C manual, a near pointer was merely 16 bits when your entire code and data fit in the one segment. A far pointer was composed of a segment as well as an offset but no normalisation was performed. And a huge pointer was automatically normalised. Two far pointers could conceivably ... |
3,575,803 | 3,579,667 | Creating a C++ DLL loadable by Lua | I have a small app that uses Lua linked as dll (not static). I want to load my own c++-written dll via Lua using package.loadlib (libname, funcname). For this purpose I need to export a function that follows the Lua's lua_CFunction protocol. Clearly for that reason I have to incorporate lua.h into my project and use Lu... | Starting with your specific questions:
Yes, but only if your DLL is implicitly linked to it. Be careful about this, because if you accidentally link two copies of the Lua VM into your application this can cause great confusion. For that matter, similar concerns apply to the C runtime as well. I would load the whole ap... |
3,575,901 | 3,578,945 | Can lambda functions be templated? | In C++11, is there a way to template a lambda function? Or is it inherently too specific to be templated?
I understand that I can define a classic templated class/functor instead, but the question is more like: does the language allow templating lambda functions?
| UPDATE 2018: C++20 will come with templated and conceptualized lambdas. The feature has already been integrated into the standard draft.
UPDATE 2014: C++14 has been released this year and now provides Polymorphic lambdas with the same syntax as in this example. Some major compilers already implement it.
At it stands ... |
3,576,024 | 3,581,120 | Suppress output to cout from linked library | I need to link my C++ programs against a couple shared libraries which generate way too much output to std::cout and std::cerr rendering them both useless for my uses. I have access to the C++ source code of these libraries, but cannot modify them.
Is there a way to redirect their output to a different stream or suppre... | Well nobody seems to have hit on it, here's my linker suggestions:
Interpose libc, provide your own write(), and filter output to file descriptors 1 and 2.
Statically link your own code against libc, and then interpose the shared version to squelch write() as above.
Interpose libc, providing a my_write() function that... |
3,576,044 | 3,576,083 | Error when using Google's protobuf | #include <google/protobuf/io/coded_stream.h>
namespace google::protobuf::io
....
int fd = open("myfile", O_WRONLY);
ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);
CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
The above is following the tutorial here, but when I compile get the fol... | Don't you mean
using namespace google::protobuf::io;
|
3,576,167 | 3,576,247 | Inherit from specialized templated base class and call the right method | I.e. I got 2 specialized types of:
template <class Type, class Base> struct Instruction {};
to compile-time-select the appropriate type from within a type list.
like:
template <class Base> struct Instruction<Int2Type<Add_Type>, Base >
{
void add() {}
};
template <class Base> struct Instruction<Int2Type<Mul_Type>,... | add() doesn't appear to depend on any template parameters (it's not a "dependent name"), so the compiler doesn't search for it in the templated base class.
One way to make it clear to the compiler that add() is supposed to be a member function/dependent name, is to explicitly specify this-> when you use the function:
v... |
3,576,275 | 3,576,321 | Different declaration and definition in c++ | I'm a bit hazy on the rules of declarations vs. definitions.
I have the following declaration in funcs.h:
void sumTotalEnrgyAndClush(Protein &A,Protein &B,double ans[2],double enrgyA[18][18],double enrgyB[18][18]);
Notice that ans[2] is before enrgyA and B.
In the funcs.cpp file the definition starts like this:
vo... |
Why doesn't the change in the order of the arguments matter?
The order does matter. In C++, functions can be overloaded, so two or more functions can have the same name if they have different parameters (or, if they are member functions, if they differ in const-qualification).
You have actually declared two sumTotal... |
3,576,616 | 3,576,722 | A basic understanding of C++ header files | I have a theory question rather than an error report.
I'm a rookie C++ programmer, trying to promote that away
Using the VC++ VS2008 compiler
I am often finding myself wondering WHY I want to take some actions in header files.
For example look at this code block:
#include "DrawScene.h"
#include "Camera.h"
#include "Pla... | Generally speaking headers should reside in the cpp file. For standard library includes (and possibly 3rd library includes) you can stick them in headers. However headers defined specifically for your project should go in cpp files whenever possible.
The reason for this is compilation time and dependency issues. Any... |
3,576,698 | 3,576,944 | Simple makefile generation utility? | Does anyone know of a tool that generates a makefile by scanning a directory for source files?
It may be naive:
no need to detect external dependencies
use default compiler/linker settings
| You can write a Makefile that does this for you:
SOURCES=$(shell find . -name "*.cpp")
OBJECTS=$(SOURCES:%.cpp=%.o)
TARGET=foo
.PHONY: all
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@
.PHONY: clean
clean:
rm -f $(TARGET) $(OBJECTS)
Just place this in root director... |
3,577,060 | 3,577,119 | How to add valid key without specifying value to a std::map? | I have a std::map, and I would like to add a valid key to iterate over it later, but without giving any value (it will be given later on in the course of the iterations).
This is how I do it for now :
std::vector<std::string> valid_keys;
//Fill... Then :
std::map<std::string, float> map;
for(size_t i = 0 ; i < valid_k... | I'm not entirely sure what you mean by "without giving any value" but if you mean without explicitly assigning a value then just do
map[valid_keys[i]];
This still works i.e. it creates a new entry in the map if there was not previously one with that key. The operator[] just returns a refernce to the value so that you ... |
3,577,077 | 3,582,154 | GlobalAddAtom() returns 0 and GetLastError = 0x5 on Win7, works on XP | Simple code:
ATOM atom = GlobalAddAtom(L"TestCpp1");
It returns 0 and GetLastError returns 0x5 (Access Denied). Nothing on MSDN about it.
This is on Win7. Admin rights make no difference.
Same code works on XP. AddAtom (local) works on Win7.
What's causing this?
| Is this a GUI or Console application? One thing you might try is to explicity call LoadLibrary("User32") before calling GlobalAddAtom.
Here is a reference to someone that had a similar problem, on XP maybe this is relevant?
http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2004-0... |
3,577,268 | 3,577,416 | boost::shared_ptr cycle break with weak_ptr | I am currently in a situation like:
struct A {
shared_ptr<B> b;
};
struct B {
shared_ptr<A> a;
};
//...
shared_ptr<A> a(new A());
shared_ptr<B> b(new B());
a->b(b);
b->a(a);
I know this won't work, because the references would continue to point to each other. I've also been told that weak_ptr solves... | Come on now.
http://boost.org/doc/libs/1_42_0/libs/smart_ptr/weak_ptr.htm
^^^^^ EXAMPLE IS RIGHT THERE ^^^^^^
DAMN!
|
3,577,365 | 3,577,386 | Output binary buffer with STL | I'm trying to use something that could best be described as a binary output queue. In short, one thread will fill a queue with binary data and another will pop this data from the queue, sending it to a client socket.
What's the best way to do this with STL? I'm looking for something like std::queue but for many items a... | What does "binary data" mean? Just memory buffers? Do you want to be able push/pop one buffer at a time? Then you should wrap a buffer into a class, or use std::vector<char>, and push/pop them onto std::deque.
|
3,577,370 | 3,577,573 | Looking for how to debug into an exported dll function in VS 9. Possible? | Got a big MFC C++ project. Our VS version is 2008. It loads a regular dll (for some optional functionality) and calls exported functions from it. When debug through the MFC app and get to the point where we call the exported function you can't step into the dll function. Is there a way to get debugging inside the ... | Debug + Windows + Modules. Locate the DLL in the list and right-click it. Symbol Load Information tells you where the debugger looked for the .pdb file. Make sure you get it there.
After update: it is very likely that with /clr enabled that you are actually running code that was compiled to IL and just-in-time compi... |
3,577,653 | 3,578,834 | C++ Inheritance: Destructor does not get called | I got my code like the following:
class TimeManager
{
public:
virtual ~TimeManager();
};
class UserManager : virtual public TimeManager
{
public:
virtual ~UserManager();
};
class Server : virutal public UserManager
{
virtual ~Server();
};
CServer *pServer;
DWORD WINAPI ServerHelper(void*);
int main()
{
//Crea... | Ok... I found the problems´ solution:
I started the main loop from within the Servers constructor:
Server::Server()
{
MainLoop(); // <- Loop in there...
}
I fixed it, by starting the server manually via an extra function and eveything is fine now :D...
Thank You to everyone who participated:)...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.