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
6,973,038
6,973,250
g++ stops on undefined reference when using -O0
I want to debug a program I wrote. Therefor I'd like to link it using "-g -O0". When I compile (using autotools Makefile) using make CXXFLAGS='-g -O0' I get some errors: libtool: link: g++ -O2 -g -O0 -I/opt/adolc-2.2.1/include -o oc_poly oc_poly-oc_poly.o oc_poly-oc_p2p.o -L/opt/ipopt-3.9.3/lib/coin -L/opt/ipopt-...
A static class member variable needs a definition; even if it is initialised in the class definition that is only a declaration. In other words, you need to put const double OCP_P2P::INF; somewhere in a cpp file. Presumably when optimisation was turned on the use of the variable was optimised out. The official rule is...
6,973,040
6,973,113
Specialize a void function template to a const char[N]
I have a templated function which I want to specialize foo to const char[N] (hardcoded strings) template<typename T> const std::string foo() ; template<typename T,int N> const std::string foo<T[N]>() { return "T[N]"; } //this doesn't work for const char[12] template<> const std::string foo<const char*>() ...
You have to do it in two steps. Since you can't partially specialize a function, you have to have the function call a class, which can be partially specialized. So the below will work. #include <typeinfo> #include <iostream> namespace detail { template <typename T> struct foo_helper { static std::string helpe...
6,973,051
6,973,097
How to create a temporary file to helping cache large data in C++?
I have some large vectors, the data of them are coming from some calculations of hard disk files. I've seen many softwares which uses a single temporary file to cache data. I'm very curious about how to do this, but I don't know the name of this technique. I want to change my codes as little as possible. Thank you. My...
I am pretty sure you're looking for memory mapped files. http://www.boost.org/doc/libs/1_47_0/libs/iostreams/doc/classes/mapped_file.html
6,973,224
6,973,483
Removing consecutive repeated characters in a string in C++
Its a string problem.First remove all repeated consecutive substring with length 1,then delete substring of length 2 and so on... for eg if we have a string like this -> abcababceccced After removing substring of length 1 we will get abcababceced After removing substring of length 2 we will get abcabced After removing ...
Indeed, linear time is possible for each substring length, since you only want consecutive identical substrings. Just keep a counter a identical characters, and update the string when you've found a substring. Since you want to remove substrings of all possible lengths, the overall complexity is quadratic. The followin...
6,973,406
6,973,431
C++ STL map container with class key and class value
So suppose I have a class like this one: class Point { private: int x, y; public: void setX(int arg_x) { x = arg_x; } void sety(int arg_y) { y = arg_y; } int getX() const { return x; } int gety() const { return y; } }; Now I want to have a map like this one: map<Point, Point> m; Bu...
You can extend your class with such a method if you don't need a separate compare function class Point { private: int x, y; public: bool operator<( const Point& other) const { if ( x == other.x ) { return y < other.y; } return x < other.x; ...
6,973,433
6,973,738
C++ templated map contain itself
I have a templated class, that can have a map type as template parameter. template<typename map_t> class my_class { map_t my_map; }; Now I'd like the value type of the map, to be equal to this class. my_class<std::map<std::string, my_class<...> > > problems; However, this is impossible to declare. How can I achie...
Since you want to be generic in the container type, the closest I have been able to find (if I understand well your intent) is: template <template <typename, typename> class Map> struct my_class { typedef typename Map<std::string, my_class>::type map_t; map_t children; }; // Since the standard doesn't allow de...
6,973,489
6,973,510
valgrind and openmp, still reachable and possibly lost, is that bad?
c++ newbie here. I've been improving my memory management skills over the last few days, and my program no longer leaks memory according to valgrind. In fact, I get no warnings from valgrind at all. However, when I add openmp loops into my code, I start to get the following errors in valgrind (memcheck): (but no defini...
Still reachable is not a memory leak. Still reachable means that a block of memory has not been freed but there are still valid pointers to the start of that block in registers or memory that has not been freed. You need to have a look at the Valgrind FAQ. The actual reason for libgomp causing the warning is explained...
6,973,543
6,973,552
how to change GUI while processing
I am new to Qt Programming, but I have basic on C++. I want to update my GUI while it is processing, example: while (....) { do some calculation... if (condition fulfill) change the color of label. } However, I realise that I failed to get the result I want (update the GUI while processi...
You have to place your processing code to another thread and update the gui, because like this GUI will be waiting for your process to end and will refresh after its end read more here: http://www.qtcentre.org/threads/41545-How-to-refresh-GUI-while-heavy-processing-is-ongoing http://www.qtcentre.org/threads/32416-Updat...
6,973,558
6,973,694
How to ensure popen()ed process runs destructors on exit?
If I have a pipe to run some command, the piped command needs to do some cleanup, however, if the processes that started the pipe has an error, the piped command is not cleaning up. Is the piped command getting SIGPIPE in this case? How can I ensure cleanupPipe destructor is always run? When the errorOccurred except...
Throwing an exception in a signal handler is a very bad idea. Signal handlers must be asynchronous-safe. To make matters worse, signal handlers run in which is essentially a different thread of execution than your mainline code. It is best to keep your signal handlers small and very primitive. For example, make the SIG...
6,973,570
6,986,579
How to add a Metadata String to an LLVM module with the C++ API?
I'm trying to add a metadata string to my LLVM module. The stripped down version of what I'm trying is #include <llvm/LLVMContext.h> #include <llvm/Module.h> #include <llvm/Metadata.h> using namespace llvm; int main() { Module* module = new Module("test", getGlobalContext()); MDString::get(module->getContext(...
Try this: #include <llvm/LLVMContext.h> #include <llvm/Module.h> #include <llvm/Metadata.h> using namespace llvm; int main() { Module* module = new Module("test", getGlobalContext()); Value *Elts[] = { MDString::get(module->getContext(), "test1") }; MDNode *Node = MDNode::get(getGlobalContext(), Elts); ...
6,973,715
6,973,744
EXC_BAD_ACCESS when setting a substring of a string to a char element of a vector (C++)
I am trying to make a vector extended header. One of the functions sets a vector to the console input (cin). It uses the following code: vector<char> cveccin(){ string cinval; cin>>cinval; vector<char> creader; for (int i=0; i<cinval.size(); i++) { creader[i]=cinval[i]; } return creader;...
The problem is that your vector is size zero, and using [] won't make it any bigger. There's a one-liner that does what you want. vector<char> cveccin() { string cinval; cin >> cinval; return vector<char>(cinval.begin(), cinval.end()); } That code creates the vector of the right size, copies the cinval str...
6,973,749
6,974,487
Checking whether #include is already declared
I am trying to check whether an #include <file.h> has already been declared using C++ macro. Example In file.h I do: #ifndef FILE.H #define FILE.H class A { //do routines }; #endif In a second file called second.h I want to check if file.h has been included already. Typical psuedo-code: #ifndef "file.h" #include "f...
Everybody else has covered correct inclusion of include guard macros. File.h #ifndef FILE_H #define FILE_H // Code here #endif But everybody else missed the second part of your question on correct usage: This is an example of bad usage: #ifndef FILE_H #include "file.h" #endif #ifndef SECOND_H #define SECOND_H ...
6,973,898
6,973,943
problem with c++ pointers in visual studio (but works in g++)
When I run the following code in Microsoft visual studio it outputs junk values (memory addresses?) but when it is run in g++ it outputs what I intend it to (with a few changes like changing srand). How do I fix it to work in visual studio? I only have a few months coding experience and this issue has been bugging me...
The members Vehicle::vin, Vehicle::gasMileage as well as Suv::fourWDStatus and Suv::fourWDGasMileage are not correctly initialized pointers. From the code you posted it seems you would be better off by changing them from pointers to regular variables (and adjusting the methods appropriately). EDIT: If using pointers is...
6,974,019
6,974,305
Noob question: Includes in Netbeans + MinGW
I downloaded this C++ project: http://lagrange.ime.usp.br/~lobato/packing/ I tried to run it on a Mac and it works wonderfully. Now i need to run it on a Windows 7 machine with Netbeans 7.0 and MinGW Compiler 5.1.6: it doesn't compile. I get errors on includes: #include <sys/resource.h> #include <sys/times.h> I found ...
Well the first step would be to comment out those #includes and see what happens. If you get compile errors then you are going to have to look at the problematic code and figure out what to replace it with. It's not the problem that's stupid it's the wonderful code you downloaded which seems to be platform specific for...
6,974,292
6,974,415
Is it safe to cast arbitrary values of the underlying type to a strongly-typed enum type?
If I have a strongly-typed enum, with say, underlying type int, is it ok to cast an int value that does not match any enumerator to the enum type? enum e1 : int { x = 0, y = 1 }; enum class e2 : int { x = 0, y = 1 }; int main() { e1 foo = static_cast<e1>(42); // is this UB? e2 bar = static_cast<e2>(42)...
From n3290, 5.2.9 Static cast [expr.static.cast]: 10 A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in tha...
6,974,319
6,974,411
Unresolved external symbol with operator overloading and templates
In trying to compile this program: namespace MyNamespace { template<typename T> class Test { public: class Inner { int x; public: Inner() : x(0) { } friend Inner& operator++(Inner& rhs); }; Inner i; }; } template<typename ...
Why do you think it can't be a member function? An instance member should work just fine: namespace MyNamespace { template<typename T> class Test { public: class Inner { int x; public: Inner& operator++( void ) { ++x; return *this; } }; I...
6,974,373
6,974,381
Weird usage of conditional operator (>?=)
I was looking at some code and saw something like this: int d = 1; int somethingbigger = 2; d >?= somethingbigger; cout << d << endl; I think this should output 2. But I can't even compile this with gcc 4.5.2. The code was written in 2005 and compiled with gcc 3.4.4 (not 100% sure). Can someone explain how this work...
This is the "maximum" assignment operator, a GCC extension. If the extension is not enabled, then you will not be able to use this feature. As of 4.0.1: The G++ minimum and maximum operators (<? and >?) and their compound forms (<?=) and >?=) have been deprecated and will be removed in a future version. Code usin...
6,974,571
6,974,712
How to make Qt Creator show error on no return statement
Turns out that g++ compiler (used in Qt Creator by default) gives a mere warning if you don't have return statement in the non-void function, i.e.: int* create_array(int n) { int* a = new int[n]; } compiles fine. This behavior is subject to countless bug reports on g++ itself, but looks like developers consider th...
This is not related to Qt but to g++. In the build options, simply add the flag -Werror and g++ will consider any warning as error. You may also need to use flag -Wall to make g++ generate additional warnings, as it doesn't generate warnings for missing return statements (and many other situations) by default. There's ...
6,974,702
6,974,779
C++ Console app, SetWindowsHookEx, Callback is never called
I have a little console application that has an embedded v8 engine, and I would like to add a hook to register key events. This all worked before when I was using Qt and QtScript, but I am porting it all over to straight C++ in VC++ 2008. The application compiles and runs, but the hook is never called, here is the rele...
A low-level hook, like WH_KEYBOARD_LL requires that your application pumps a message loop. That's the only way that Windows can break into your thread and make the call to the HookProc callback you registered. A console mode app doesn't pump a message loop like regular Windows GUI apps do. Judging from your snippet, ...
6,974,893
6,974,921
Calculating time of execution with time() function
I was given the following HomeWork assignment, Write a program to test on your computer how long it takes to do nlogn, n2, n5, 2n, and n! additions for n=5, 10, 15, 20. I have written a piece of code but all the time I am getting the time of execution 0. Can anyone help me out with it? Thanks #include <iostream> #i...
Execute each calculation thousands of times, in a loop, so that you can overcome the low resolution of time and obtain meaningful results. Remember to divide by the number of iterations when reporting results. This is not particularly accurate but that probably does not matter for this assignment.
6,975,097
6,975,141
How to extract part of a string in c++
To Extract part of a string in a given line: Given line is: D:\AB554P_Itr23\ModelDir\AB554P_approximation_NodeData.dat Read 3/18/2010 I need to extract only the file name AB554P_approximation_NodeData.dat. I am using CodeGear RAD Studio C++ Builder. Thanks:)
The RTL function ExtractFileName() will extract the file name from a path. Exactly how to split the 3 fields in your example depends very much on what the rules are for forming that line of text. How is it delimited? Is is delimited by spaces? If so, how do you escape spaces in the file path? Until you specify that inf...
6,975,154
6,975,187
C++ array initializer. Using enum type
class ARouter { enum directions {north, neast, east, seast, south, swest, west, nwest}; static directions gon[] = {north, neast, nwest, east, west, seast, swest, south}; }; Hi, does anyone know what is the matter with the above code? I am getting 2 errors for the second line from VC++2008Ex: error C2059: synt...
You cannot define a variable inside a class like that. It needs to be something like: class ARouter { enum directions {north, neast, east, seast, south, swest, west, nwest}; static directions gon[]; }; ARouter::directions ARouter::gon[] = {north, neast, nwest, east, west, seast, swest, south}; The declaration...
6,975,189
6,975,245
How this stdout redirection works?
Code below redirects stdout to a file fname & then redirects back to original stdout. It works fine for me. But I am not able to understand how it actually works. If anyone can help me understand I will appreiciate it. printf("\n This is console"); fflush(stdout); fgetpos(stdout, &pos); fd = dup(filen...
Let's go through it line by line. The first line prints something to stdout: printf("\n This is console"); Then it flushes stdout so all the remaining data in the buffer gets sent to stdout and won't get mixed up with the file data: fflush(stdout); Now we store the current position of ourselves in stdout because othe...
6,975,198
6,975,454
wxGetElapsedTime function in wxWidgets 2.9+
I'm trying to follow some old C++ tutorial which use old version o wxWidgets framework (2.6 I think), but I have complied version 2.9.1, where I could not find wxGetElapsedTime() and wxStartTimer() methods. The elapsed time method is used as argument to srand() method to 'randomize' initial random seed value and the au...
try srand((int)wxGetLocalTime()); and wxStopWatch * stopWatch = new wxStopWatch(); updateSomethingByTime( stopWatch->Time() );
6,975,261
6,976,263
C++ Profiling on mac
I'm writing STL-only C++ application on mac(OS X Lion / XCode 4.1). I need to answer a simple question: which parts of code must be optimized? Gprof does empty output, XCode's Instruments doesn't help. Which tool I need to use?
Use Shark. It's in /Developer/Applications/Performance Tools Very easy to use. More here: http://developer.apple.com/tools/sharkoptimize.html
6,975,267
6,975,299
C++ Saving file with unicode name problem - How to save UTF-8 filenames correctly in a crossplatform manner?
I want to save a file with name Привет Мир.jpg I receive a string (read it from file for example) (with unicode in it) but my C++ code saves it as ÐÑÐ¸Ð²ÐµÑ ÐиÑ.jpg What shall I do to save it correctly? (btw if I just save that string into file it saves correctly, meaning only the way I save filename is some whay wron...
The C++ standard library is not Unicode aware. Therefore, you must use a library (like Boost.Filesystem) that is Unicode aware. Alternatively, you have to deal with platform-specific issues. Windows supports UTF-16, so if you have UTF-8 strings, you need to convert them to UTF-16 (std::wstring). Then you pass those as ...
6,975,295
6,977,427
Using JNI to load another JNI library?
I need to implement a native method, let's say "public native void someFunc();". I have two libraries, libabc.so and libdef.so. Java uses System.loadLibrary(); to load libabc.so (which does not implement the method), but the JNI implementation is in libdef.so. Currently, I'm doing the following in libabc.so. JNIEXPORT ...
While I still don't have a solution for the problem of loading another JNI library in JNI_OnLoad, I found the first native function that is called, replaced it, and in that function, I run the loadLibrary code. Then I call the native method again from JNI and it runs the new version of the method.
6,975,497
6,983,238
Change QML font.pointSize in C++
I have managed to change the "color" property of QML text with C++ using this: theText->setProperty("color", "red"); but if I try theText->setProperty("font.pointSize", 20); then nothing happens(it's not that size), I've tried this with other things that include a "." but none seem to work, I think the "." may be pa...
Look for actual property name. And as far as i know there is no sub-properties in QObjects... So you need something like this: QFont f = theText->property("font").value<QFont>(); f.setPointSize(20); theText->setProperty("font",f);
6,975,578
6,977,083
linkage between dllimport and dllexport
I have some question concerning dllexport, dllimport in C++ in Windows. Let's assume I have some module.cpp and module.h which export functions using dllexport. Let's assume that I also have moduleWrapper.cpp and moduleWrapper.h which imports functions from module.cpp using dllimport. Can somebody please explain why ca...
From what I understand, you have something like this in module.h: __declspec(dllexport) void f(); And then, you have a similar statement in your moduleWrapper.cpp: __declspec(dllimport) void f(); That counts as a function declaration, so you remove any need to include module.h. The way it's commonly done is by puttin...
6,975,619
6,976,538
Which version of the Windows SDK uses xinput1_3.dll?
I currently have Windows SDK 7.0A installed. This version of the SDK contains Xinput.h which references xinput9_1_0.dll: #define XINPUT_DLL_A "xinput9_1_0.dll" I need my program to use xinput1_3.dll instead. I figured that in order to do this, I must link with the xinput.lib file from an earlier version of Windows SD...
I think the solution is actually to use the Microsoft DirectX SDK (June 2010) by modifying the include and library dirs for your project. The XInput.h file from the DirectX SDK... // XInput.h from the DirectX SDK #ifndef XINPUT_USE_9_1_0 #define XINPUT_DLL_A "xinput1_3.dll" #define XINPUT_DLL_W L"xinput1_3.dll" #else...
6,975,621
6,976,164
not properly closing from taskbar closing event
if i close my application via Alt-F4, or the corner "X" button, or by posting destroywindow(hwnd) myself, the application closes correctly, and everything works just as expected. but recently i realized, on windows7, when i close the app by right klicking on the icon in the taskbar, and clicking "Close Window", the win...
You should get WM_CLOSE. Maybe you're getting it on a different window that the one you're expecting? Although that shouldn't be able to happen unless you have multiple top-level windows.
6,975,658
6,978,841
Reading a binary file in Java vs C++
I have a binary file (about 100 MB) that I need to read in quickly. In C++ I could just load the file into a char pointer and march through it by incrementing the pointer. This of course would be very fast. Is there a comparably fast way to do this in Java?
If you use a memory mapped file or regular buffer you will be able to read the data as fast your hardware allows. File tmp = File.createTempFile("deleteme", "bin"); tmp.deleteOnExit(); int size = 1024 * 1024 * 1024; long start0 = System.nanoTime(); FileChannel fc0 = new FileOutputStream(tmp).getChannel(); ByteBuffer b...
6,976,161
6,976,246
boost disable_interruption not preventing thread_interrupted
I am trying to prevent interruption of a thread while it is in a particular scope. However, using boost::this_thread::disable_interruption di() does not seem to have any effect. #include <boost/thread.hpp> #include <iostream> void worker() { std::cout << "START" << std::endl; for(;;) { { b...
You should remove parenthesis in the following line: //boost::this_thread::disable_interruption di(); boost::this_thread::disable_interruption di; Instead of creating disable_interruption object, you declared function di.
6,976,276
6,976,294
Makefile with macro, does not generate any executable
I wrote a Makefile(code below) for my program which contains hello.h, hello.cpp and main.cpp (this is a trivial testbench for hello.cpp). However, after I type make in the terminal, it tells me make: `hello.o' is up to date. Can someone give any hints? Thank you! #MACRO CAT_HOME = $(MGC_HOME) TARGET = my_tb #OBJEC...
You define a TARGET variable but later try to use $(TARGETS). Theres an S in difference. Also, it is inefficient to let every .o file depend on every .cpp file. You might as well just write a linear script that recompiles everything unconditionally. Since you're depending on make's built-in rule for creating a .o from ...
6,976,306
6,976,481
JNI Native Method causing VM crashing
I'm implementing a Java method as Native in C++ JNIEXPORT jobjectArray JNICALL myMethod(JNIEnv *env, jclass, //parameters){ int** result = //my function to obtain a matrix n x m of integers std::vector<jint> tmp; //fill the vector tmp with matrix integers and deallocate the matrix for (int i = 0; i < ...
Your current code as I'm writing this: JNIEXPORT jobjectArray JNICALL myMethod(JNIEnv *env, jclass, //parameters){ int** result = //my function to obtain a matrix n x m of integers std::vector<jint> tmp; //fill the vector tmp with matrix integers and deallocate the matrix for (int i = 0; i < n; i++){ ...
6,976,309
6,976,325
Why 'q' and 'r' cannot be use as function?
So I'm trying to return the perimeter and area in int main, but g++ keeps throwing error messages. Please help in explanation of error. Thanks. Source: 1 // This program takes in two values and returns the perimeter and the area of the values taken. 2 3 #include<iostream> 4 using namespace std; 5 6 double...
Because you have defined q and r as doubles, then you are trying to 'call' them like a function with your ()s Edit Also, like the other answers state, depending on what you want to do - you either need to define q and r as functions (like you have done with area and perimeter or you need to call your two existing funct...
6,976,458
6,976,487
Why is std::sin() and std::cos() slower than sin() and cos()?
Test code: #include <cmath> #include <cstdio> const int N = 4096; const float PI = 3.1415926535897932384626; float cosine[N][N]; float sine[N][N]; int main() { printf("a\n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cosine[i][j] = cos(i*j*2*PI/N); sine[i][j]...
You're using a different overload: Try double angle = i*j*2*PI/N; cosine[i][j] = cos(angle); sine[i][j] = sin(angle); it should perform the same with or without using namespace std;
6,976,489
6,976,514
C++ Exceptions; int or std::exception?
I am writing some library functions that needs to do some error reporting. I want to use exceptions rather than return values. I wrote my functions that throws int exceptions. Eg: if(strm->atEnd()){ // unexpected end of stream throw -2; } My question is, is this method OK? Or should I throw a exception derived...
I would throw an exception based on std::exception. throw std::runtime_error("unexpected end of stream") I find this easier to catch, log, et cetera. It also allows the removal of a comment and a magic number from the code. This message can then be sent to the end-user to give them a hope of fixing the problem. Users ...
6,976,657
6,977,162
How do you compile Box2D for Code::Blocks/MinGW32 under Windows?
I've found similar questions across the internet, none of which helped me. The Code::Blocks workspace and project files included DO generate .a files, and I've moved them to Codeblocks/MinGW/lib, and I've moved the Box2D folder to Codeblocks/MinGW/include and yet the HelloWorld.cpp example still gives me these errors.
Looks like the project files you used to build the .a were missing some files. The file mentioned in the error message is one that was removed from Box2D after v2.1.2, so I'm guessing you are using 2.1.2 source code (or thereabouts) with project files from some other source? In any case, setting these up yourself is re...
6,976,759
6,976,832
How do I make VS2010 prefer one include directory over another?
I'm trying to use the XInput.h file from the DirectX SDK, but this file also exists in the Windows SDK (and it's a different variation of the file). I've tried adding $(DXSDK_DIR)Include; to the Include Directories in the project settings, before and also after $(IncludePath) just to try and make it work. I got VS to c...
I had the same problem trying to use the August 2007 DirectX SDK (for DirectDraw) with Visual Studio 2010. What I ended up doing was removing all of the default include paths, and only specifying the DirectX SDK path in the include list, then checking "Inherent from parent or project defaults", which includes the frame...
6,976,940
6,977,008
C++ executable - MSVCR100.dll not found error
I've downloaded and compiled an open-source C++ application, Frhed. When I run the version I've compiled, it demands MSVCR100 and few other dll files (part of Visual C++ redistributable). However, when I run the original precompiled Frhed executable, it runs without any C++ redistributable package installed. Do I have ...
The original program is probably statically linked, whereas you are trying to dynamically link your executable, which results in a smaller file, but a dependency on functions inside MSVCR100.dll (v10 of the Microsoft C Runtime Library), which would have been included inside the executable if you were statically linking...
6,976,992
6,977,002
fwrite() File Corruption C++
I'm somewhat of a newbie to C++ (moving from C#) so I'm not exactly sure what's going on here. What I'm trying to do is read an image out of a file and write it to an output file, but whenever I do parts of the file appear to be corrupt. I've checked the data in memory and it actually matches, so I believe the culprit...
Are you running this code on Windows? For files that don't need text translation, you must open them in binary mode: FILE* output = fopen(CStringA(outputFileName), "wb+"); This is what happens in your output file: 07 07 07 09 09 08 0A 0C 14 0D 0C 07 07 07 09 09 08 0D 0A 0C 14 0D 0C ^^ The C runtime...
6,976,999
6,977,014
Question about C++ character pointer
I'm still very new to C++ and I'm very confused about something that looks like this: int main() { char* aCharPointer = "A bunch of characters"; return 0; } Why can you do that with a character pointer? Perhaps there is another place with the answer but I don't know where to look or what I'm ...
This has to do with strings in C (and make no mistake, that IS a C string). Strings are an array of characters. The following code: char* txt = "Hello"; Produces the following character array: H|e|l|l|o|\0 And txt points to the first element. The last element is a null terminator, and it's how anything using the stri...
6,977,065
6,977,148
C++ refuses to run properly unless cout is used
This code compiles, but refuses to make a ball jump when there is no cout. When there is a cout, it properly makes the object (dot) jump. This is just a bit of practice using SDL to create a super primitive game Main loop: while (!quit){ while (SDL_PollEvent(&event)) if ((event.type == SDL_QUIT) || ((event....
I'm pretty sure it's not something specific to using cout. It only has to do with the amount of time that using cout takes. That inner loop that the cout statement is in has nothing controlling it's pace. It just controls the jump for what? 2 milliseconds, right? During that 2 milliseconds, the dot goes through as m...
6,977,094
6,980,290
QT Application --- WIFI connection
Does QT have any APIs for detecting wireless networks? If not, are there any other cross-platform means of detecting wireless networks?
Qt has no wifi support out of the box, wifi is too platform-specific. Use native API's for working with wifi.
6,977,158
7,818,731
JavaCv/OpenCv error: what does it mean?
I'm using JavaCv with OpenCv 2.3 from Java (on Windows). Occasionally something goes wrong, and OpenCv throws an error, something like: OpenCV Error: Bad argument (unrecognized or unsupported array type) in unknown function, file ..\..\..\..\ocv\opencv\modules\core\src\array.cpp, line 995 With the following Java stac...
If you allocate your IplImage using IplImage.create(), you should not call cvReleaseImage() manually on it. <- This is most likely the cause of the error. Either call IplImage.release() or let the garbage collector deallocate it for you, at some point in the future...
6,977,492
6,977,504
Am I using gcc wrong?
I've been having no end of trouble just getting started with C++. Seems like no matter what I do, I've got dozens of errors. I've taken to compiling example code from tutorials, but even the example code doesn't compile. For example, the code at: http://www.cppgameprogramming.com/cgi/nav.cgi?page=arrayclasses gives me ...
You have to include dog.cpp in the compilation: g++ main.cpp dog.cpp -o dog Alternatively, you can compile dog.cpp by itself to an object file, and include that in the final compilation: g++ dog.cpp -c -o dog.o g++ main.cpp dog.o -o dog
6,977,554
6,977,562
Is there any way to change an outside object from inside a function
Is it possible to define a function which will make the argument refer to another (already existing) object after it returns without using pointers, etc? Again, this can't just change the existing object by using a copy constructor or assignment operator or anything. The outside object would refer to a different block ...
No, because something and x are different objects. They don't refer to different objects. They don't point to different objects. They are different objects. To change where something points, that something needs to be a pointer. If you have a pointer, you can do this: int x; void change(int*& p) { p = &x; } i...
6,977,747
6,977,760
.cpp error: no match for 'operator<' in 'std::cerr < "Converting file \""'
I'm trying to execute this code nmea2kml.cpp but I keep getting the following errors. Also the program has command line parameters -f path Read file at given path (e.g. /some/where/nmea.txt) What should I change to run the program? Am I getting the error due to a compiler problem? coz I've messed up with adding cygwin...
It looks like you have written std::cerr < "..." (the < operator) where you meant to write std::cerr << "..." (the << operator).
6,977,810
6,978,581
Including other files in c++ for File I/O
Is there a way to add files to the final .exe in a c++ program ? For example, suppose I want to play a sound file. Instead of including the sound file separately with the release .exe, the file should be part of the exe. Im aware about the use of resource files, in C++. This article on the MSDN website, says that it is...
Suggestion: Actually, the easiest way is to simply append the binary contents to the end of the .exe. Append a 4-byte "length" value after that. It will not affect your ability to run the .exe. Then, at runtime: 1) Open your .exe as a binary file, read-only. 2) fseek (or equivalent) to .exe size - 4. 3) read the len...
6,977,820
6,979,349
Interfaces and covariance problem
I have a particular class that stores a piece of data, which implements an interface: template<typename T> class MyContainer : public Container<T> { class Something : public IInterface { public: // implement *, ->, and ++ here but how? private: T x; }; // implement begin and end her...
What you are trying to do is called type erasure. Basically you want to provide a value type (which is the same across the whole inheritance hierarchy) that wraps the particular iterator type and offers a uniform dynamic interface. Type erasure is usually implemented with a non-virtual class (the type erased) that stor...
6,977,828
6,979,348
wxWidgets Widget for representing std::map?
I'm working on a level editor for my game engine, and I've run into a small problem. Game objects can have values associated with them, each value having a name and a value (yes, I know this is redundant, it came up repeatedly when getting everything set up). I need a widget that will allow me to represent a map of val...
If you want a widget to view a std::map then I think wxPropertyGrid should be what you want. It has a pretty extensive example under samples/propgrid in your wxWidgets install.
6,977,847
6,977,886
Macro to count (character) arguments
I have a macro to convert a string to a list of characters: #define TO_STRING(x) #x #define CHAR_LIST_7(x) TO_STRING(x)[0] \ , TO_STRING(x)[1] \ , TO_STRING(x)[2] \ , TO_STRING(x)[3] \ , TO_STRING(x)[4] \ ...
You can't split tokens during preprocessing, you can only combine them (using ##). Converting the identifier to a string literal won't help either as you can't string split a string literal apart during preprocessing, nor can you perform operations (e.g. compute length) on a string literal. During preprocessing the com...
6,977,939
6,977,964
Computing lg(N!): Anyone have a Better Recursive Method?
I think the title of the post addresses my question. But just to reiterate, I am wondering if anyone has a better approach to this problem. /* Write a recursive program to compute lg( N! ) */ #include <iostream> #include <cmath> using namespace std; long double log_base2( long double N ) { return log( N )/log( ...
Just do it iteratively? I don't see a reason this problem needs to be solved recursively. If you have a requirement (For some reason or other) to do it recursively your way appears to work fine, although your base case can just be to return 0 (log(1) in any base is 0). Also, there's no need to convert to base 2 at each...
6,978,182
6,978,225
Implicit convert CString to char*
I have downloaded an sample code, so there are some CString variables in that code which are passed to the sscanf() function as char* the compiler implicitly converts those CString and the code complie fine.the code which works fine is here: CString m_strVersionXFS; m_strVersionXFS = _T("00029903"); DWORD nVersion; s...
I suspect that your own code is using unicode (UNICODE constant defined). This means that CString is using wide characters, and will implicitly convert to wchar_t*, but not to char*. If that is the case, there are three possible solutions: Use swscanf, the wide character version of sscanf (recommended); Explicitly use...
6,978,185
6,978,373
HTTP Post Response parsing in C++
I am writing puzzle bot, http server which upon hitting , renders a default page with text area to write code similar to http://codepad.org/. When I type in following program. #include <stdio.h> int main( int argc, char **argv) { return 0; } I get following response from HTTP POST. code : %23include+%3Cstdio.h%3E%...
You need to decode the data, first. You could use this reference . All spaces are replaces with the sign +, and all numbers after % are special - 2 digit hex encoded numbers - URL encoded special symbols (like +, ,, }, etc.). For example, you code will be translated to : #include <stdio.h>\r\nint main( int argc, char...
6,978,241
6,978,266
"undefined reference to" using 'g++' to compile a C++ program
I can't seem to get the errors to go away. The errors are below. I have looked on Google Search and still I can't figure it out. It is not like I am new to C++, but I have not fooled around with it in a while. The weird thing is it worked with g++ on Windows... Errors using: g++ main.cpp Output: /tmp/ccJL2ZHE.o: In f...
Use g++ main.cpp Help.cpp You have to tell the compiler all the files that you want it to compile, not just the first one.
6,978,652
10,005,299
How do I use RestartManager to restart explorer.exe with Windows Installer custom action?
I have an installer that prompts users to restart their computer after an install. I would rather not have the user restart their computer in this case, and have explorer.exe just restart itself using the RestartManager API provided with Windows Vista and up. I've created a separate executable that gets copied to the l...
I ended up reaching a solution to this... Rather than creating a separate executable that registers explorer.exe and shuts it down, create a MSI DLL Custom Action. All this DLL has to have is a single function that registers explorer.exe to be restarted and use the existing restart manager session provided by Windows I...
6,978,675
6,978,869
How to make QT Application write a crash log
i am working on project developed in Qt, Windows, i use Qt Version 4.1.4 and VC6 IDE for compiling project, most of usage of product are on WindowsXp. i frequently receive crash reports from testers and customers which does not have fix pattern and does not reproduce in my development environment. so i come to the conc...
For cross-platform application Breakpad is probably better solution. But easy way for Windows -is to set unhandled exception handler via SetUnhandledExceptionFilter and write minidumps (with configuration you need) with WriteMiniDumpEx in handler. example
6,978,811
6,978,958
Strongly typed enums without explicit scoping?
I want strong enum types. C++0x has this feature but unfortunately they also require explicit scoping: enum class E {e1, e2, e3}; E x = E::e1; //OK E y = e1; //error Sometimes this is desirable, but sometimes it's just unnecessarily verbose. The identifiers might be unique enough by themselves or the enum might alread...
If you want the values visible in the surrounding scope, just add a couple of constants: enum class E {e1, e2, e3}; const E e1 = E::e1; const E e2 = E::e2; const E e3 = E::e3;
6,979,256
6,979,342
QMake Linking Problem With GCC
I have a problem with qmake and the make file that it generates. My program needs to be linked against two libraries. I add them in main.pro as follows. LIBS += -L lib/somelib1/bin -lsomelib1 -L lib/somelib2/bin -lsomelib2 How ever I arrange the above line qmake tells gcc this. g++ -o programname someobject.o -L lib/s...
You should not put spaces between the flags and the arguments: LIBS += -Llib/somelib1/bin -lsomelib1 -Llib/somelib2/bin -lsomelib2 Or LIBS += -L"lib/somelib1/bin" -lsomelib1 -L"lib/somelib2/bin" -lsomelib2 And why are your static/import libraries in the "bin" directory? There should be .a files in the "lib" director...
6,979,424
6,979,473
How to put a conditional breakpoint to test if a CString variable is empty
So I have this simple code snippet: CString str; .................. if ( str.IsEmpty() ) str = spRelease->GetID(); I want to put a conditional breakpoint on the last line to test if str is empty. I tried this first: str == "" But I get this: Error overloaded operator not found Then this: str.isEmpty() == 0 And g...
Why don't you just put a normal breakpoint on the last line? You already know str is empty. If you want to double check whether your string is empty, I would use an ASSERT instead. If you really have to check your string, you have to check m_pszData in your CString, so your condition looks like this: str.m_pszData[0] =...
6,979,491
6,979,586
How to delete warnings LNK4217 and LNK4049
I have warnings on the link step. These warnings appear only in release mode. My program is composed of two parts: a library which generates a .lib and an executable which uses this library. When I build the library I have no warnings. But when I build my executable, on the link I have warnings LNK4217 and LNK4049. F...
It's caused by __declspec(import) on the symbols mentioned as "imported", ie. on public: __thiscall std::exception::exception(char const * const &). That may be caused by mismatch between compiler option for runtime selection (/MT (static multi-threaded runtime) v.s. /MD (dynamic runtime)) and the preprocessor options ...
6,979,548
6,979,616
storing value Turbo C++
I am currently trying to get my program to store a value so that it can display that value whenever there is an error. Here is my program : void function() { float abc[2]; int i = 0; if ( i/2 != 0 ) { i++; abc[0] = 1; } abc[1] = abc[0]; cout << abc[1]; } Practically, my prog...
I'm not sure exactly what result you are trying for, but you need to make abc and i static, thusly: void function() { static float abc[2]; static int i = 0; if ( i/2 != 0 ) { i++; abc[0] = 1; } abc[1] = abc[0]; cout<<abc[1]; } This will allow them to retain their value between function calls. Righ...
6,979,569
6,979,628
Writing custom for loop in c++
I wondered if that would be possible, a custom for loop. The one I had in mind was the foreach expression from java, which is for(Container c : Element e){ // do stuff with e } I wanted to write it for a custom container I wrote (lets call it cust_cont), which I wanted to work with a foreach loop (like the one...
Not sure I understand your question, but yes, you have to implement begin() and end() methods (ideally overloaded on const) in order for iteration to work on your custom container. Also, you need nested iterator and const_iterator types (or typedefs). To summarize, here is what you need: member types: MyClass::iterato...
6,979,612
6,979,712
Why constructors will always have same name as of class and how they are invoked implicitly?
I want to know that why the name of constructor is always same as that of class name and how its get invoked implicitly when we create object of that class. Can anyone please explain the flow of execution in such situation?
I want to know that why the name of constructor is always same as that of class name Because this syntax does not require any new keywords. Aside from that, there is no good reason. To minimize the number of new keywords, I didn't use an explicit syntax like this: class X { constructor(); destructor(); } In...
6,979,826
6,979,955
Where can I find the declaration of HOST_E_CLRNOTAVAILABLE (type HRESULT) constant?
Could anyone, please, help me to find the header file, which contains the declaration of HRESULTs returned by ExecuteInDefaultAppDomain() function. The compiler doesn't see the values documented in MSDN: HOST_E_CLRNOTAVAILABLE, HOST_E_NOT_OWNER etc. Note, that <MSCorEE.h> is included.
Those codes are in CorError.h. Just #include <corerror.h> and they'll be available.
6,979,848
6,986,306
Horizontal line in QTextEdit
I'm trying to put an horizontal line in a QTextDocument. I'm using HTML for the formatting. To draw the line I want, I naturally used the <hr /> tag. But the line is drawn gray and and I'd like to change its color to black. The styles doesn't seem to apply on the hr element, so is there a simple workaround to have hor...
Coming from HTML, <hr> does not really have the ability to be colored or formatted. IE did it with color, Mozilla with background-color etc. So the best (both in HTML/css and QTextDocument) is to avoid <hr> and take instead any very small element, size it appropriately and give it a border and a background-color of sam...
6,979,918
6,983,388
Compile ATL project with only Windows SDK 7.1
I have a project which needs to be compiled. It is compiled on our build server which I have only installed Windows SDK 7.1 on. I would like to not have to install an actual Visual Studio on this machine, but am getting an error "cannot find atlstr.h" file which I've just read is part of ATL which is part of Visual Stu...
ATL is now freely available as a part of Windows Driver Kit: http://msdn.microsoft.com/en-us/windows/hardware/gg487438.aspx
6,980,308
6,980,482
Number of messages in 'unbounded_buffer'
The class Concurrency::unbounded_buffer can store any number of messages. But how to know number of pending (not received) messages?
There's no functionality built in to do this. What you can do is atomically increment/decrement an integer alongside it, but know that this won't be a reliable count (only a ballpark) if it's being accessed concurrently. long count; Concurrency::unbounded_buffer<T> buffer; if(Concurrency::send(buffer, T())) { long...
6,980,522
6,980,817
Problems using tr1::regex with unicode strings
std::wstring str(L"something"); std::tr1::wregex rx(L"something"); std::tr1::wcmatch res; std::tr1::regex_search(str, res, rx); This fails to compile with the error: error C2784: 'bool std::tr1::regex_search(const std::basic_string<_Elem,_StTraits,_StAlloc> &,const std::tr1::basic_regex<_Elem,_R...
You should be using wsmatch, which is for wstring iterators, not wcmatch, which is for wchar_t*.
6,981,193
7,009,688
How can I set assembly look-up path after initiating CLR?
Is there a way (an API function) to set the C# assembly lookup path after starting CLR Host, so that, ExecuteInDefaultAppDomain() function find it? thanks in advance.
Seems there are only two ways to specify an assembly's locations. Unfortunately, none of them works for this case. Thereby, having the possible lists of assembly's directories and the name of the assembly, one needs to locate the file manually and then pass the full path to ExecuteInDefaultAppDomain() function. However...
6,981,222
6,981,258
Storing an image file into a buffer (gif,jpeg etc).
I'm trying to load an image file into a buffer in order to send it through a scket. The problem that I'm having is that the program creates a buffer with a valid size but it does not copy the whole file into the buffer. My code is as follow //imgload.cpp #include <iostream> #include <stdlib.h> #include <stdio.h> using ...
You are wrong. Image is binary data, nor string data. So there are two errors: 1) You can't check end of file with EOF constant. Because EOF is often defined as 0xFF and it is valid byte in binary file. So use feof() function to check for end of file. Or also you may check current position in file with maximal possible...
6,981,616
6,981,870
Using Crypto++ to generate random hashes with SHA1
I need to generate a random hash using Crypto++, using SHA1. At the moment I have: #include <cryptopp/sha.h> #include <cryptopp/filters.h> #include <cryptopp/hex.h> ... CryptoPP::SHA1 sha1; string source = "Hello"; //This will be randomly generated somehow string hash = ""; StringSource(source, true, new HashFilter...
Just specify your namespaces correctly and carefully: #include <cryptopp/sha.h> #include <cryptopp/filters.h> #include <cryptopp/hex.h> #include <string> int main() { CryptoPP::SHA1 sha1; std::string source = "Hello"; //This will be randomly generated somehow std::string hash = ""; CryptoPP::StringSource(sou...
6,981,641
6,983,377
Embedding Mongoose Web Server in C++
I just embedded the Mongoose Web Server into my C++ dll (just a single header and recommended in most of the stack overflow threads) and I have it up and running properly with the very minimal example code. However, I am having a rough time finding any sort of tutorials, examples, etc. on configuring the very basic nec...
1) "enable_directory_listing" option 2) Not built into Mongoose (at least not the version I have, which is about 6 months old). [EDIT:] Newer versions of Mongoose support throttling download speed. From the manual... Limit download speed for clients. throttle is a comma-separated list of key=value pairs, where key...
6,981,787
7,101,757
Can I get object name from a symbol information in the symbol table in an ELF file?
I have successfully parsed an elf file (executable file) compiled from multiple source files. I am able to get the binding(local,global,weak), type(object,file,section,function), size of the symbol and the address of the symbol along with the symbol name ( from string table). The section to which the symbol is linked i...
You cannot get the object file name directly, this is lost during linking. However, depending on the build process used to create the executable, you can infer the object file name from the STT_FILE symbols (e.g., an executable contains a STT_FILE symbol with name foo.c -> you could maybe infer the object file was foo....
6,981,860
6,982,202
Is it possible to create such C++ macros that would wrap your standard (inherited) class into an application?
So we have simple interface base class: class animal { public: animal(int age) : age_(age) { } virtual ~animal(void) { } virtual std::string get_name(void) { return "A generic animal"; } int get_age(void) { return age_; } protected: int age_; }; And we want ti inherit from it with a class lik...
int main() { int default_age = 4; SERVICECLASS *an_animal = new SERVICECLASS(default_age); std::cout << "anmal "<< an_animal->get_name << " created. Its age is " << an_animal->get_age << std::endl; std::cin.get(); } Then compile with (your compiler's equivalent of) -DSERVICECLASS=puma, or have a file called something ...
6,982,078
6,982,109
How to create documentation for a c++ project?
I am using the Ubuntu OS to create a library written in c++. I've created an shared library and now I need to document my work. I would like to know what is the smartest and fastest way to do it?
If you're looking for API documentation of your classes / types, you might want to look into Doxygen.
6,982,130
11,256,939
How to prevent Eclipse creates nmake file instead of make?
In order to develop qt application on eclipse, i have installed mingw, qt and qt eclipse integration. When i try to build the project, it search nmake for building project and syntax of my make file is nmake syntax. And i thought there were some special eclipse settings but i could'nt find anything about it. ...
It is because of Qt version. Nmake is special for Visual Studio integrated Qt. So If your eclipse create nmake file instead of make file. Your eclipse show wrong version of Qt. If you don't want to get this error. You should firstly check: Check you download true eclipse version. The Qt version which eclipse is usin...
6,982,158
6,982,219
Function-scope static object's constructor throws an exception
Consider the following code: #include <iostream> struct X{ X(){ throw 0; } }; void f(){ static X x; } int main(){ try { f(); } catch(int) { std::cout << "Caught first time" << std::endl; } try { f(); } catch(int) { std::cout << "Caught second time" << std...
It is guaranteed that the construction will be attempted as long as it fails. It's caused by what is stated in C++03 §6.7/4: ... Otherwise such an object is initialized the first time control passes through its declaration; such an object is considered initialized upon the completion of its initialization. If the init...
6,982,167
7,233,600
CUDA: please help me to find error in my code
There's code, that uses GPU: __global__ void gpu_process(float* input, float* weights, float* output, int psize, int size) { int i = blockIdx.x*blockDim.x + threadIdx.x; int j = blockIdx.y*blockDim.y + threadIdx.y; if(i < psize && j < size) output[j] += input[i] * weights[i * size + j]; } void proce...
cudaThreadSyncronize is deprecated and should not be used, instead use cudaDeviceSyncronize, check the error codes of these, since they will return an error if a thread has failed. These also block all code thereafter until the task is completed, so you could also add some timing code inbetween to find bottlenecks.
6,982,259
6,982,513
OpenGL concept question
I'm just starting OpenGL programming in Win32 C++ so don't be too hard on me :) I've been wandering along the NeHe tutorials and 'the red book' a bit now, but I'm confused. So far I've been able to set up an OpenGL window, draw some triangles etc, no problem. But now I want to build a model and view it from different a...
First you need to understand, that OpenGL actually doesn't understand the term "model", all what OpenGL sees is a stream of vertices coming in and depending on the current mode it uses those streams of vertices to draw triangles to the screen. Every frame drawing iteration follows some outline like this: clear all buf...
6,982,470
6,982,633
could not deduce template argument?
I have the following class template<typename hi_t, typename lo_t> struct int_t { hi_t hi; lo_t lo; int_t() : lo(0), hi(0) {} int_t(int value) : lo(value), hi( value<0u? -1: 0 ) {} int_t(unsigned value) : lo(value), hi( 0 ) {} int_t& operator+=(const int_t& rhs) { lo_t _lo = lo; lo += rhs.lo; hi += rhs.hi...
The code is trickier than it seems at first look. The most tricky part is your declaration of a friend function. You should take a look at this answer regarding befriending a function from a template. The short recommendation is that you remove the templated operator+ and you implement it as a non-template friend funct...
6,982,585
6,983,915
Is D's grammar really context-free?
I've posted this on the D newsgroup some months ago, but for some reason, the answer never really convinced me, so I thought I'd ask it here. The grammar of D is apparently context-free. The grammar of C++, however, isn't (even without macros). (Please read this carefully!) Now granted, I know nothing (officially) abo...
Being context free is first a property of generative grammars. It means that what a non-terminal can generate will not depend on the context in which the non-terminal appears (in non context-free generative grammar, the very notion of "string generated by a given non-terminal" is in general difficult to define). This...
6,982,689
6,982,772
how to end-up template layers?
When having: template <typename Super> class Whatever : public Super { ... }; is it possible, to create Whatever class without deriving from something? Is this the lighter version? struct BlankType{}; Whatever<BlankType> w; //////////////////////////////////////// Some background: I have my code composed into te...
If you want to create Whatever class that is not derived from something you can simply define its specification as follows: class BlankType {}; template<typename T = BlankType> class Whatever : public T {}; template<> class Whatever<BlankType> {};
6,982,971
6,983,089
Comparing a string with a regEx wildcard value
So I need to check a string (url) against a list of reg ex wildcard values to see if there is a match. I will be intercepting an HTTP request and checking it against a list of pre-configured values and if there is a match, do something to the URL. Examples: Request URL: http://www.stackoverflow.com Wildcards: *.stac...
The following code example uses regular expressions to look for exact substring matches. The search is performed by the static IsMatch method, which takes two strings as input. The first is the string to be searched, and the second is the pattern to be searched for. #using <System.dll> using namespace System; using ...
6,983,233
6,983,283
Waiting for unzip to finish before carrying on C++ code on a RedHat machine
I want to unzip a zipped folder on my Redhat machine. To do this I send a bash script the string; "unzip /usr/bin/Folder.gz" This unzips the folder no problem, as in I get the general inflating folderA/folderB/fileX etc. However, I want to hold the code at the unzip command, waiting until the unzipping is complete. ...
How do you run the bash script? If you use the system() API it will start the program and then wait until the spawned process ends. system() system is a call that is made up of 3 other system calls: execl(), wait() and fork(). Source.
6,983,237
6,983,519
C++ DirectShow Video and Audio capture - beginning
I have finally managed to drop working with VFW after several problems I have encountered during the application development. Thanks to StackOverflow, I am now aware that VFW is obsolete and wish to switch to DShow, to let my application work with Vista/W7. Unfortunately, the work has been made and application has been...
Your best bet for examples will be the ones from Microsoft. Your questions are still phrased in terms of VFW so it's hard to answer them as written. For example, in DirectShow you wouldn't register a callback for to encode a video frame. Instead, you'd develop an encoder filter that would receive data from the capture ...
6,983,273
6,983,339
Using a char* to store the correct file path
It has been a while since I messed with C/C++, and my memory of the available functions for working with a char* has gone out the window. I currently use the following code to get the Current Working Directory... char *path = NULL; size_t size = 0; path = _getcwd(path, size); Msg("Current Working Directory: %s\n", pat...
Okay - to keep your life complicated.. use strrchr to find the last \ use memcpy (unless you have strncpy) to copy number of characters to that point. I should add that 1. will return the last \, so you if your path is like C:/foo/bar/, it will stop at / - so you'll have to do some boundary checks... I did say "to ke...
6,983,303
6,983,353
Can C++ macros add some code to the end of C++ file?
So I have code like: // puma.cpp #include "FILE_WITH_MACROS.hpp" ANIMAL_MACROS_NAME_HERE class puma : public animal { public: puma(int age) : animal(age) {} virtual std::string get_name() { return "puma"; } }; //end of puma.cpp and here we want to add some more code via ANIMAL_MACROS_NAME_HERE macros. Can ...
No, but you can always add another macro in the end of the file. In some cases it can be possible to do something like this: #define MY_CLASS_WITH_END_STUFF(derived, parent) \ ANIMAL_MACROS_NAME_HERE class derived : public parent \ { \ public: \ ... \ }; \ // here you can add stuff now as pa...
6,983,385
6,983,513
OOP Sockets don't wait for accept()
we have the exercise to program a webserver in object oriented style. So we created a class for WinSockets. We wanted to loop the main part (from accept till send) to handle connections one by one (just to start up; multithreading will be implemented later). Problem: The first time, a connection got established everyth...
I think you're confused. You should normally have 2 sockets: 1 for accepting connections (you already have this one) and 1 for exchanging data (returned as new_fd from call to accept() in WinSocket:akzeptieren()). In most frameworks, a big distinction is made between listener sockets and stream sockets: // oversimplif...
6,983,403
6,983,450
Function Pointer basic question
I have a basic question on function pointer. In the below code snippet, how do I read this " *(FARPROC*)&pfn ="? IFastString *CallCreateFastString(const char *psz) { static IFastString * (*pfn)(const char *) = 0; if (!pfn) { const TCHAR szDll[] = _TEXT("FastString.DLL"); const char szFn[] = "CreateFastString"; HIN...
This isn't really about function pointers, but about casting in general. Suppose pfn is of type T. Then &pfn is of type T*. This gets cast to FARPROC* by the cast expression (the stuff in the parentheses). Finally, this gets dereferenced, yielding a FARPROC&. All in all this just means you're treating pfn as if it were...
6,983,517
6,983,548
String.h Errors From g++ Compilation
I cannot make heads or tails of the following C++ error generated by g++ /tmp/ccH0IPVU.o: In function `myAPP::mandatory_bitfield_t::to_s(std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)': myAPP.cpp:(.text._ZN3myAPP20mandator...
As far as the linker knows, you have forgotten to include (compile) a definition of myAPP::to_s(unsigned char*, int). I'm just translating the error message. Cheers & hth.
6,983,572
7,257,831
Looping inside Google's CTemplate
how can I loop in google-ctemplate lib inside a template ?
Sections are google-ctemplate answer for loops and conditions. Syntax: {{#SECTION_NAME}} Section contents. Can have nested sections. {{/SECTION_NAME}} Iterate over sections 0 or 1 times - and you'll get if statement. Iterate n times - and you'll get loop.
6,983,914
6,983,964
what is the standard guideline to declare the "==" condition?
Possible Duplicate: What is the difference between these (bCondition == NULL) and (NULL==bCondition)? please see the below code:- if(myVariable==5) { //some logic } one of my friends says that this is not a good way to write the code as its not per guidelines, however he dont have any reason to it. Is th...
The only reason to write: 5 == variable instead of variable == 5 is that in the former case if you incorrectly put an assignment (single =) in place you will get a compile time error because you are trying to overwrite a constant. However any decent compiler will give you a warning if you do: if (variable = 5) so IM...
6,984,029
6,984,106
Can I call a windows DLL from a linux client?
I found this command line in a tutorial: gcc -o Client1 Client1.o CodeSample1.dll -lgdi32 -lm and made me wonder when is possible to call a windows DLL from a linux client, or well, a Linux .so file from a windows client. Are there any constraints such as language, name decoration, etc?
I have a suspicion that you're not actually trying to ask what you asked. The .dll file in your example is just a shared library. You can link against shared libraries with GCC. The only question is what you call your library: // Stage 1: Build and link the library: gcc -c -o mylib.o mylib.c // Compile gcc ...
6,984,092
6,984,109
Windows API gui designer?
Is there a good GUI designer (read: drag 'n drop/WYSIWYG) for the plain old Windows API? I'm not looking for something that uses Qt, GTK, .NET, etc, just plain old Windows API. Must be usable with either C or C++.
You are looking for a resource editor. Visual Studio Professional, Premium and Ultimate have one built into the IDE. You can access it by creating a new .rc file and then adding a resource to it. If you're not using Visual Studio you can use an external resource editor such as ResEdit. Not having it built into the IDE ...
6,984,096
6,984,218
Retrieving the position of the phone using GPS in Qt
I want to know the longitude and the latitude of the phone, and for that I must use the QtLocation library. For best results, which class and function should I use?
The information comes from the Qt Mobility class QGeoPositionInfoSource. You will find an example here.
6,984,444
6,984,606
Using "namespace foo {" instead of explicitly qualifying outside of header files
If a function is declared as such: namespace foo { void bar(); } Most people define the function like this: void foo::bar() { ... } However I like to do it this way: namespace foo { void bar() { ... } } I prefer this style because its saves me from always retyping foo::, which is often tediou...
If you use the foo::bar form, and accidentally define the function with incorrect arguments, you will get a compiler error. If you put the definition in a namespace in the source file, different arguments will simply result in a different function being defined. You won't get an error until you try to link with code ...
6,984,491
6,984,682
How Curly Brackets work in Boost::extension, how to make such macros on my own?
I look at how we use Boost::Extension BOOST_EXTENSION_TYPE_MAP_FUNCTION macro. For example like this: BOOST_EXTENSION_TYPE_MAP_FUNCTION { std::map<std::string, boost::extensions::factory<service> > &factories(types.get()); factories["file_service"].set<file_service>(); } BOOST_EXTENSION_TYPE_MAP_FUNCTION macro...
Let me put my comment into an answer... A macro is an instruction to the compiler (I use the collective term here) to substitute at that location the symbols defined as that macro, for example #define FOO 1 int val = FOO; // at this point, FOO is replaced with 1 (p.s. please don't do this in C++) Now, what is happeni...