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
2,200,025
2,200,076
Declare types without implicit conversion in C++
I want to declare my own numeric types, exactly like unsigned int, but I do not want the types to be implicitly converted. I tried this first: typedef unsigned int firstID; typedef unsigned int secondID; but this is no good as the two types are just synonyms for unsigned int, so are freely interchangable. I'd l...
Maybe BOOST_STRONG_TYPEDEF form boost/strong_typedef.hpp would help.
2,200,068
2,200,085
How can I control the order heap objects are destroyed?
Let's say I have 2 singletons, allocated on the heap, for which no delete is ever called. Let's call them A and B. Is there any way to make sure B will be the first one to be destroyed? I'm assuming the platform may matter on this one: Visual Studio 2005 Professional, Visual C++. Everything was built with cl.
If they are heap allocated to normal pointers, and if delete is never called on those pointers, then they will never be destroyed, so the order of destruction is moot. On the other hand, If you allocate them to static smart pointers, and if they are in the same translation unit, then the first one created will be the ...
2,200,207
2,834,772
Objective-C++ Memory Problem
I'm having memory woes. I've got a C++ Library (Equalizer from Eyescale) and they use the Traversal Visitor Pattern to allow you to add new functionality to their classes. I've finally figured out how it works, and I've got a Visitor that just returns the properties from one of the objects. (since I don't know how...
I suppose I should answer and close this out. The methods I was using were completely thread-unsafe. I was calling out across threads, Carbon/Cocoa, C++/ObjC. Needless to say, don't ever do that! I learned the hard way. -Stephen
2,200,257
2,200,306
How can I retrieve current terminate() handler without changing it?
Here's the problem. My application calls CoCreateInstance() to create a COM object implemented in a third-party DLL. That DLL calls set_terminate() to change the terminate() handler and passes an address of its own terminate() handler there. The initial terminate() handler address is not saved by that library - it does...
Standard C++ provides no built-in way. Of course you could just call terminate() twice: first time with whatever dummy handler you have (and then store handler that terminate() returned you); second -- to restore handler you've just stored ;) Simple trick.
2,200,277
2,200,786
Detecting debugger on Mac OS X
I am trying to detect whether my process is being run in a debugger or not and, while in Windows there are many solutions and in Linux I use: ptrace(PTRACE_ME,0,0,0) and check its return value, I did not manage to perform the same basic check on Mac OS X. I tried to use the ptrace(PT_TRACE_ME,0,0,0) call but it al...
You can just call the function AmIBeingDebugged() from Apple Technical Q&A QA1361, which is reproduced here because Apple sometimes breaks documentation links and makes old documentation hard to find: #include <assert.h> #include <stdbool.h> #include <sys/types.h> #include <unistd.h> #include <sys/sysctl.h> static boo...
2,200,394
2,200,401
Link error in C++ by g++
Please take a look at the program below. Why am I getting an error? #include <stdlib.h> #include <string> #include <string.h> #include <iostream> using namespace std; class serverData { public: static int serverTemp; static int server; }; int main(int argc, char** argv) { string s = "sajad bahmani"; ...
Static member variables must have storage allocated in one of your .CPP files: /* static */ int serverData::serverTemp; int serverData::server;
2,200,421
2,200,761
QT4 Memory Management
I come from a fairly strong C background, and have a rather solid foundation in C++. More recently I've been working with C# and other higher level languages. A project I'm looking at working on could really benefit from using QT4, but I have some questions on memory management I can't seem to understand. I've read the...
If I create a QList and add objects to it, and then the QList goes out of scope, will it try to deallocate the child objects? QList is just like std::list. It will destroy the contained objects when it is destroyed. If a Qt4 routine returns a pointer to an object, am I then responsible for the de-allocation of that ...
2,200,528
2,200,726
C++ Manipulator not being executed
Well, I'm wondering why endd doesn't seem to execute (though it doesn't generate any error at compilation time). struct dxfDato { dxfDato(int c, string v = 0, int t = 0) { codigo = c; valor = v; tipo = t; } dxfDato() { } int tipo; int codigo; string valor; }; class dxfItem { private: std::ostri...
You've defined type manip to be a function that takes a std::ostream by reference and returns a std::ostream by reference, but you've defined endd to take a dxfItem and return a dxfItem and dxfItem does not derive from std::ostream. Because of this type mismatch, the compiler is generating a call to the operator<< temp...
2,200,530
2,200,633
Iterate Multiple std::vector
I've read here and other places that when iterating a std::vector using indexes you should: std::vector <int> x(20,1); for (std::vector<int>::size_type i = 0; i < x.size(); i++){ x[i]+=3; } But what if you are iterating two vectors of different types: std::vector <int> x(20,1); std::vector <double> y(20,1.0); for (s...
Yes, for almost any practical purpose, you can just use std::size_t. Though there was (sort of) an intent that different containers could use different types for their sizes, it's still basically guaranteed that (at least for standard containers) size_type is the same as size_t. Alternatively, you could consider using ...
2,200,646
2,200,684
How do you declare a const array of function pointers?
Firstly, I've got functions like this. void func1(); void func2(); void func3(); Then I create my typedef for the array: void (*FP)(); If I write a normal array of function pointers, it should be something like this: FP array[3] = {&func1, &func2, &func3}; I want to make it a constant array, using const before "FP",...
Then I create my typedef for the array: void (*FP)(); Did you miss typedef before void? Following works on my compiler. void func1(){} void func2(){} void func3(){} typedef void (*FP)(); int main() { const FP ar[3]= {&func1, &func2, &func3}; } EDIT (after seeing your edits) x.h class x; typedef ...
2,200,912
2,201,715
Inheritance in Python C++ extension
I have c++ library that need communicate with Python plugged in modules. Communication supposes implementing by Python some callback c++ interface. I have read already about writing extensions, but no idea how to develop inheritance. So something about: C++: class Broadcast { void set(Listener *){... } class Liste...
Writing Python types in C that are inheritable is explained in PEP 253. It's not all that different from writing a normal builtin type as explained in the Extending/Embedding guide but you have to do certain things, like attribute access, through the Python API instead of accessing anything directly. Exposing the Pytho...
2,201,012
2,201,196
In C++ how can I prevent a function from being called recursively
I have a function which makes use of memory on the heap and it will go badly wrong if it is called before another instance of the same function has completed. How can I prevent this from happening at compile time?
Detecting recursion with any amount determinism of at compile-time is going to be quite difficult. Some static code analysis tools might be able to do it, but even then you can get in to run-time scenarios involving threads that code analyzers won't be able to detect. You need to detect recursion at run-time. Fundame...
2,201,131
2,201,183
Linker error with pointers
I am trying to build a program to Tolkinize a string (i'm trying to do this with out using the string class - so as to learn more about pointers and how chars work) - I have built a program that i think works (any suggestions would be great!) When i tried to compile the program I get these random errors: Error 1 error...
It looks like you're not compiling/linking tokenize.cpp. It's probably not the code itself, but how you have it setup in Visual Studio. Is it possible that VS isn't including tokenize.cpp in your application? You can test that this is the problem by moving the functions from tokenize.cpp to main.cpp. If the errors go a...
2,201,220
2,220,253
Why is my MFC DLL deadlocking on a single thread near startup?
Using Visual Studio 2005, the debugger tells me that a deadlock has occurred just after startup of the app I'm writing - I'm well in to WinMain() at this point. The callstack shows that we are in a critical section, while calling AFX_MANAGE_STATE2 (for the 666th time, spookily enough) from within an MFC DLL. This has...
I discovered that another member of my team had called TerminateThread rather than CloseHandle in a function a few instructions earlier. Fixing that fixed the problem. I shall look in to WINDBG though. Thread problems do crop up now that we're living in a multi-core world.
2,201,263
2,201,410
Pure base class needs to be exported from DLL?
I have two DLLs: a.dll and b.dll and in each one I have one class AClass and BClass. I would like to have both AClass and BClass inherit and implement the same interface AbsBase which is a pure abstract class. In each class I set up the #defines for __declspec(dllimport) and __declspect(dllexport). When I'm trying to c...
It looks like its a compiler warning and not an error, so it should still work. The compiler is just letting you know that you are doing something that makes it easy for you to screw up. It should be perfectly acceptable to do this as long as both DLLs and the core program agree on the definition of the base class. You...
2,201,296
2,201,377
How to create a resizable window with rounded-corners in win32
I'm trying to create a Win32 window that has rounded corners and is resizable both horizontally and vertically. My first approach was to create BITMAP of a rounded rectangle and draw it to the screen in conjunction with setting the windows style to WS_EX_LAYERED and setting the transparency key to the outside color of ...
I would try to mix the Windows API functions CreateRoundRectRgn and SetWindowRgn. A very simple example can be found at pInvoke.net web site.
2,201,420
2,201,498
A good place to learn about image processing in c/c++?
any websites, books etc. If someone would like to share their own experiences. thank you
This is a free book which runs through some recurring tasks in computer vision and image processing. Regarding the C++, you can take a look at OpenCV which is a computer vision library written in c/c++
2,201,493
2,201,509
Using default in a switch statement when switching over an enum
What is your procedure when switching over an enum where every enumeration is covered by a case? Ideally you'd like the code to be future proof, how do you do that? Also, what if some idiot casts an arbitrary int to the enum type? Should this possibility even be considered? Or should we assume that such an egregious ...
I throw an exception. As sure as eggs are eggs, someone will pass an integer with a bad value rather than an enum value into your switch, and it's best to fail noisily but give the program the possibility of fielding the error, which assert() does not.
2,201,918
2,202,244
conversion of multiple ascii characters in a char array to single int using their ascii values --- c/c++
anyone know a good way for doing this conversion? for example, take the char array holding ascii charcters "ABC", the int conversion i'm looking for would change those characters to a single int with value 656667. any help would be very much appreciated. edit really appreciate the replies. as someone noted i did say ch...
Most of the time, one got to look at the actual problem. Parsing a packet protocol may or may not be easy, depending on the specification, but you can usually do better than throwing it all in a string... If you don't know about them, look up Google Protocol Buffer, they can't be used as is, but the idea is there. clas...
2,202,179
2,202,321
Problem using yaml-cpp on OS X
So I'm having trouble compiling my application which is using yaml-cpp I'm including "yaml.h" in my source files (just like the examples in the yaml-cpp wiki) but when I try compiling the application I get the following error: g++ -c -o entityresourcemanager.o entityresourcemanager.cpp entityresourcemanager.cpp:2:18...
Your default target is "mac" and you have rule how to build it. It depends on object files and you do not have any rules how to build those, so make is using its implicit rules. Those rules do just that: g++ -c -o entityresourcemanager.o entityresourcemanager.cpp As you can see there is no -I/usr/local/... part her...
2,202,262
2,205,988
Map from integer ranges to arbitrary single integers
Working in C++ in a Linux environment, I have a situation where a number of integer ranges are defined, and integer inputs map to different arbitrary integers based on which range they fall into. None of the ranges overlap, and they aren't always contiguous. The "simplest" way to solve this problem is with a bunch o...
I would use a very simple thing: a std::map. class Range { public: explicit Range(int item); // [item,item] Range(int low, int high); // [low,high] bool operator<(const Range& rhs) const { if (mLow < rhs.mLow) { assert(mHigh < rhs.mLow); // sanity check return true; } return false...
2,202,322
2,202,384
Calling a custom type from a DLL written in C++ from c#
I'm using a DLL written in c++ in my C# project. I have been able to call functions within the DLL using this code: [DllImport("hidfuncs", EntryPoint = "vm_hid_scan", ExactSpelling = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr VmHidScan(); Now I need...
Given the "P" prefix, it looks like the real declaration is hid_get_info(int n, DEV_INFO **pdi) where DEV_INFO is a structure. You'll need to find the declaration of this structure and add it to your C# code with the [StructLayout] attribute. You'd then declare the function like this in your C# code: [DllImport("bla...
2,202,460
2,202,467
CreateObject equivalent in C/C++? (COM Interop)
What would the equivalent in C/C++?
It's the CoCreateInstance() function. It is convenient to use CoCreateInstance when you need to create only a single instance of an object on the local machine. If you are creating an instance on remote computer, call CoCreateInstanceEx. When you are creating multiple instances, it is more efficient to ...
2,202,512
2,203,022
how do i turn my program into something i can install?
how do i turn my VC++ 2008 program into something i can get to run on other computers. i have tryed using the .exe it makes in the debug but it will say that im missing some files and lists all of my .cpp file names and .h files(if i use it on other computers). i wanted something so i could encrypt my files because one...
You generally can't and almost never should distribute debug builds to client machines. At least three reasons. Client machines will not have the debug versions of your dependant libraries, like the VC runtime (msvcrtd.dll), so they won't be able to run your app. When compiling in debug, your code will in many ways...
2,202,534
2,202,658
How to generate pseudo random in cuda
I am attempting to build a particle system utilizing CUDA to do the heavy lifting. I want to randomize some of the particles' initial values like velocity and life span. The random numbers don't have to be super random since it's just for visual effect. I found this post that addresses the same subject: Random Numbe...
CUDA pseudo random number generators are included in the NVidia SDK eg C/src/MersenneTwister/ and C/src/quasirandomGenerator available as separate papers and source: 2.a Langdon's paper and Langdon's source code 2.b Mersenne Twister on GPU
2,202,585
2,202,792
Does using a C++ namespace increase coupling?
I understand that a C++ library should use a namespace to avoid name collisions, but since I already have to: #include the correct header (or forward declare the classes I intend to use) Use those classes by name Don't these two parameters infer the same information conveyed by a namespace. Using a namespace now int...
It sounds to me like your problem is due primarily to how you're (ab)using namespaces, not due to the namespaces themselves. It sounds like you're throwing a lot of minimally related "stuff" into one namespace, mostly (when you get down to it) because they happen to have been developed by the same person. At least IMO...
2,202,731
2,202,906
Is there support in C++/STL for sorting objects by attribute?
I wonder if there is support in STL for this: Say I have an class like this : class Person { public: int getAge() const; double getIncome() const; .. .. }; and a vector: vector<Person*> people; I would like to sort the vector of people by their age: I know I can do it the following way: class AgeCmp { public:...
Generic adaptor to compare based on member attributes. While it is quite more verbose the first time it is reusable. // Generic member less than template <typename T, typename M, typename C> struct member_lt_type { typedef M T::* member_ptr; member_lt_type( member_ptr p, C c ) : ptr(p), cmp(c) {} bool operato...
2,203,093
2,203,124
Should C# or C++ be chosen for learning Games Programming (consoles)?
I've basic game programming knowledge in c and c++. I'm learning c# nowadays. If I want to make a career in console games programming, which one I should use to proceed? I've noticed that a lot of game companies are using C++/C (probably because of legacy reasons). Also probably C++ enjoys more number of supported libr...
C++, for two reasons. 1) a lot of games are programmed in C++. No mainstream game is, as yet, programmed in a managed language. 2) C++ is as hard as it gets. You have to master manual memory management and generally no bounds checking (beyond the excellent Valgrind!). If you master C++, you will find this transferab...
2,203,159
2,203,694
Is there a C++ equivalent to getcwd?
I see C's getcwd via: man 3 cwd I suspect C++ has a similar one, that could return me a std::string . If so, what is it called, and where can I find it's documentation? Thanks!
Ok, I'm answering even though you already have accepted an answer. An even better way than to wrap the getcwd call would be to use boost::filesystem, where you get a path object from the current_path() function. The Boost filesystem library allows you to do lots of other useful stuff that you would otherwise need to d...
2,203,257
2,203,277
Effect on performance when using objects in c++
I have a dynamic programming algorithm for Knapsack in C++. When it was implemented as a function and accessing variables passed into it, it was taking 22 seconds to run on a particular instance. When I made it the member function of my class KnapsackInstance and had it use variables that were data members of that clas...
In a typical implementation, a member function receives a pointer to the instance data as a hidden parameter (this). As such, access to member data is normally via a pointer, which may account for the slow-down you're seeing. On the other hand, it's hard to do more than guess with only one version of the code to look a...
2,203,388
2,206,549
Templates polymorphism
I have this structure of classes. class Interface { // ... }; class Foo : public Interface { // ... }; template <class T> class Container { // ... }; And I have this constructor of some other class Bar. Bar(const Container<Interface> & bar){ // ... } When I call the constructor this way I get a "no matching...
I think the exact terminology for what you need is "template covariance", meaning that if B inherits from A, then somehow T<B> inherits from T<A>. This is not the case in C++, nor it is with Java and C# generics*. There is a good reason to avoid template covariance: this will simply remove all type safety in the templa...
2,203,592
2,203,609
How can I link an .o file using g++
I am trying to use g++ to compile a .cc file, and I need it to link a .o file. So I tried: $g++ -o client -I../ipc -L../messages.o client.cc /usr/bin/ld: error: ../messages.o: can not read directory: Not a directory And I have tried: $g++ -o client -I../ipc -l../messages.o client.cc /usr/bin/ld: error: cannot find -l....
$g++ -o client -I../ipc client.cc ../messages.o
2,203,695
2,203,720
What is the address of back() in an empty container?
I mistakenly took the address of the reference returned by the back() operator in an empty container and was surprised to see that the address wasn't zero. If a container e.g. std::deque is empty, what does back() return?
it returns the last element. on this page: http://www.sgi.com/tech/stl/BackInsertionSequence.html precondition: !a.empty() Equivalent to *(--a.end()). since the precondition is the deque is not empty, then it means it's undefined behavior.
2,203,831
8,869,865
hiphop PHP download?
Where can you download the HipHop Code? I would really like to test it. Interestingly enough if you go here: http://github.com/facebook/hiphop-php/wikis It must not exist or private because it redirects to github.com index.php page So you can not even see the wiki or anything
git clone git://github.com/facebook/hiphop-php.git
2,203,946
2,206,667
error while loading shared libraries
I'm trying to install Code::Blocks from source. There is an `anarchy' folder on my university's CS department's mainframe, where anyone can install anything, basically. wxwidgets is a dependency of Code::Blocks, and I'm trying to put wxGTK, as it's called, into my own folder on `anarchy', which works fine. I then compi...
This is how I solved this: First I ran the configure script like this: $ ./configure --prefix=/pub/anarchy/<myname>/codeblocks --with-wx-config=/pub/anarchy/<myname>/wxGTK/bin/wx-config then: $ export LDFLAGS="-Wl,-R /pub/anarchy/<myname>/wxGTK/lib" $ make $ make install Now codeblocks finds libwx_gtk2u-2.8.so.0. An ...
2,204,176
2,204,380
How to initialise memory with new operator in C++?
I'm just beginning to get into C++ and I want to pick up some good habits. If I have just allocated an array of type int with the new operator, how can I initialise them all to 0 without looping through them all myself? Should I just use memset? Is there a “C++” way to do it?
It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for value-initializing an array: new int[10](); Note that you must use the empty parentheses — you cannot, for example, use (0) or anything else (which is why this ...
2,204,608
2,204,628
Does C++ call destructors for global and class static variables?
From my example program, it looks like it does call the destructors in both the cases. At what point does it call the destructors for global and class-static variables since they should be allocated in the data section of the program stack?
From § 3.6.3 of the C++03 standard: Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (18.3). These objects are destroyed in the reverse order of the completion of their con...
2,204,941
2,213,245
How to determine whether an LSA session is active in Windows XP
I'm trying to get the list of users currently logged into a machine. On Windows 7, I can call LsaEnumerateLogonSessions, then WTSQuerySessionInformation with WTSConnectState. But on XP, each LSA session has 0 for the TS Session field (unless it's a Remote Desktop session), which always has WTSConnectState of WTSActive,...
I believe this codeproject article uses a workaround that might be what you are after, it enumerates all running processes, checking the AuthenticationId (TokenStatistics on the process token) against the list of LUID's LsaEnumerateLogonSessions gives you. This allows you to filter out stale LUID's
2,205,044
2,205,087
How to hardcode a value in a texbox in c++
I am using the below code to popup the authentication dialog. I want to hard-code the password in my code and make it a read-only text box. What should I do? IDD_LOGIN_AUTH_DIALOG DIALOG DISCARDABLE 0, 0, 148, 82 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Authentication" FONT 8, "MS Shell Dl...
You get full control over all fields if you use the CONTROL keyword rather than the EDITTEXT keyword, use CONTROL "mypassword", IDC_PASSWD_EDIT, "Edit", ES_LEFT | WS_BORDER | ES_PASSWORD | ES_READONLY, 84,41,57,12 instead of EDITTEXT IDC_PASSWD_EDIT,84,41,57,12,ES_PASSWORD | ES_READON...
2,205,152
2,205,238
automatically skipping/ignoring external code in gdb
Possible Duplicate: How to avoid entering library's source files while debugging in Qt Creator with gdb? anybody know how to tell gdb to only enter code that is in your project? I know it's hard for a debugger to know what is "in the project" and what is a library....but I thought some naive checks could help, eg do...
As per my opinion this cannot be done. every project has a flow of data from one function to other. gdb is designed to work on the flow of data. so if your project is somewhere in the middle of the flow,gdb cant help you,since evry function has some purpose to do with the input it gets and output it gives. all you can ...
2,205,211
2,205,219
Rounding with static_cast<int>?
I feel really silly asking this because I know how to do it 101 ways, but not the way it is defined in the book. (note, I know C++) So far, we have only gone over the very basics of C++. So basically, we know variables, assignment, and basic casting. In the book I am having trouble with this portion of the problem: p...
static_cast<int>(n+0.5) Or static_cast<int>(n >= 0 ? n + 0.5 : n - 0.5) for more proper behavior on negative n.
2,205,239
2,206,241
Any useful suggestions to figure out where memory is being free'd in a Win32 process?
An application I am working with is exhibiting the following behaviour: During a particular high-memory operation, the memory usage of the process under Task Manager (Mem Usage stat) reaches a peak of approximately 2.5GB (Note: A registry key has been set to allow this, as usually there is a maximum of 2GB for a proce...
Ahh! You're looking at the wrong counter! Mem Usage doesn't tell you that memory is being freed. Only that the working set is being purged! This could mean some other application needs memory, or the VMM decided to mark some of your process's pages as Stand By for some other process to quickly use. It does not mean tha...
2,205,353
2,205,394
Why doesn't this reinterpret_cast compile?
I understand that reinterpret_cast is dangerous, I'm just doing this to test it. I have the following code: int x = 0; double y = reinterpret_cast<double>(x); When I try to compile the program, it gives me an error saying invalid cast from type 'float' to type 'double What's going on? I thought reinterpret_cast was ...
Perhaps a better way of thinking of reinterpret_cast is the rouge operator that can "convert" pointers to apples as pointers to submarines. By assigning y to the value returned by the cast you're not really casting the value x, you're converting it. That is, y doesn't point to x and pretend that it points to a float. ...
2,205,404
2,205,505
How to flush file buffers when using boost::serialization?
I'm saving a file on an USB drive and need to make sure that it's completely written to avoid corruption in case the USB drive is not removed properly. Well I've done some research and it seems this is possible via calling the FlushFileBuffers Win32 function. But the problem is, I'm saving using boost::serialization an...
Call ostream::flush on the output stream you created your archive object with: // create and open a character archive for output std::ofstream ofs("filename"); boost::archive::text_oarchive oa(ofs); ... ofs.flush(); You could also just let the objects go out of scope which should flush everything: { // create an...
2,205,583
2,206,392
Iterate through struct variables
I want to get an iterator to struct variable to set a particular one on runtime according to enum ID. for example - struct { char _char; int _int; char* pchar; }; enum { _CHAR, //0 _INT, //1 PCHAR //2 }; int main() { int i = 1; //_INT //if i = 1 then set variable _int of struct to some value. } can you do ...
No, C++ doesn't support this directly. You can however do something very similar using boost::tuple: enum { CHAR, //0 INT, //1 DBL //2 }; tuple<char, int, double> t('b', 1, 3.14); int i = get<INT>(t); // or t.get<INT>() You might also want to take a look at boost::variant.
2,205,587
2,205,631
How to call unmanaged c++ function that allocates output buffer to return data in c#?
I have problems with marshalling output parameter of c++ function returning array of data to c#. Here is C++ declaration: #define DLL_API __declspec(dllexport) typedef TPARAMETER_DATA { char *parameter; int size; } PARAMETER_DATA; int DLL_API GetParameters(PARAMETER_DATA *outputData); The functio...
The problem you're facing is that a pointer is returned - not really a string or an array. There is no way for the marshaller to convert the pointer to an array or string, because the length is unknown. The solution might be to do the pointer handling in c#. You should also figure out if you're responsible for freeing ...
2,205,603
2,205,796
Conditional dependency with make/gmake
Is there a way to direct make/gmake to act upon conditional dependencies? I have this rule in place: $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(CPPC) -c $(FLAGS_DEV) $< -o $@ In the general case, every .cpp file has a corresponding .h file; however there are a few exceptions. Is there a way to achieve "depend on this if it...
A better way to do this, is to actually determine the dependencies of the cpp files with gcc -MM and include them in the makefile. SRCS = main.cpp other.cpp DEPS = $(SRCS:%.cpp=$(DEP_DIR)/%.P) $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(CPPC) -c $(FLAGS_DEV) $< -o $@ $(DEP_DIR)/%.P: $(SRC_DIR)/%.cpp $(CPPC) -MM $(FLAGS_DE...
2,206,050
2,206,082
How to convert a string literal to unsigned char array in visual c++
How to convert a string to Unsigned char in c++... I have, unsigned char m_Test[8]; I want to assign a string "Hello world" to m_Test. how to do it?
Firstly, the array has to be at least big enough to hold the string: unsigned char m_Test[20]; then you use strcpy. You need to cast the first parameter to avoid a warning: strcpy( (char*) m_Test, "Hello World" ); Or if you want to be a C++ purist: strcpy( static_cast <char*>( m_Test ), "Hello World" ); If you ...
2,206,165
2,271,200
Language codes in platform SDK 6.1
Language codes are in the form "en-US","de-DE" or "sl-SI" for English US, German and slovakian respectively. Whether there is any #define s present in PLATFORM SDK 6.1 for language codes. Its better if i got these values instead of using Hard coded strings in my program. Can anyone help me regarding this. Its better if...
There are no # defines present for language codes. We can use the function LocaleNameToLCID() to get the language ID for given language code. Thanks all for help!!
2,206,366
2,206,408
Conditional operator in member-initialization list
Suppose I have this class: class foo { public: foo() { } foo(const std::string& s) : _s(s) { } private: std::string _s; }; Which is a member of another class: class bar { public: bar(bool condition) : _f(condition ? "go to string constructor" : **go to empty ctor**) { } private: ...
The result of a conditional operator is always a fixed type determined at compile time by finding a common type that both options can be converted to. (The exact rules are a little involved, but in common use it usually 'does the right thing'.) In your example the simplest thing to do is to let that type be a temporary...
2,206,729
2,206,760
Returning reference to class with overloaded private & operator?
I got a class called Property (from external library == cannot be modified) that has private overloaded & operator. I use this class in another class as a property and (for sanity reasons) I'd like to return a reference to this property through the Get method. However I got the 'cannot access private member declared in...
I may be missing something, but why not simply say: const Property& GetProperty() const { return this->m_Property; } The fact that the operator& is private pretty clearly indicates that you are not supposed to call it.
2,206,742
2,206,863
Pass a variable number of arguments to an aliased function
Take a function like printf that accepts a variable number of arguments what I would like to do is pass these variable number of functions to a sub function without changing their order. An example of this would be aliasing the printf function to a function called console ... #include <stdio.h> void console(const cha...
Here's what you want: #include <stdio.h> #include <stdarg.h> void console(const char *_sFormat, ...); int main () { console("Hello World!"); return 0; } void console(const char *_sFormat, ...) { va_list ap; va_start(ap, _sFormat); printf("[APP] "); vprintf(_sFormat, ap); printf("\n"); ...
2,206,782
2,206,840
Should i override operators new/delete in my c++ WIn32 applications
I know Microsoft themselves used to recommend overriding operator new with calls to HeapCreate() and HeapAlloc(), but that was a while ago. See KB139638 for more details. Would i still benefit from overriding new/delete on Win32? What would be the recommended implementation? TIA.
The article says you can do it, not that you should. The code in it is so badly written it isn't funny, and it is not thread safe. In general, the implementation supplied new and delete will work well for all general programming needs. You should only consider re-implementing them if you have identified a specific pro...
2,206,844
2,207,153
Should I use "this" to call class properties, members, or methods?
I've seen some guides or blogs that say using this to access a class's own members is bad. However, I've also seen some places where professionals are accessing with this. I tend to prefer explicitly using this, since it seems to make it clear that the thing I'm accessing is part of the class. this.MyProperty = this.Ge...
Having gone from using this for years, to finding not many people (atleast in my experience) use it, I eventually changed. The benefits I can see of having this-less code: I use underscores: _myVar for private variables, which don't need a this as they're always member variables. For method calls it is very obvious t...
2,207,006
2,207,257
Modular Exponentiation for high numbers in C++
So I've been working recently on an implementation of the Miller-Rabin primality test. I am limiting it to a scope of all 32-bit numbers, because this is a just-for-fun project that I am doing to familiarize myself with c++, and I don't want to have to work with anything 64-bits for awhile. An added bonus is that the...
Exponentiation by squaring still "works" for modulo exponentiation. Your problem isn't that 2 ^ 168277 is an exceptionally large number, it's that one of your intermediate results is a fairly large number (bigger than 2^32), because 673109 is bigger than 2^16. So I think the following will do. It's possible I've missed...
2,207,053
2,207,188
What are app domains used for?
I understand roughly what an AppDomain is, however I don't fully understand the uses for an AppDomain. I'm involved in a large server based C# / C++ application and I'm wondering how using AppDomains could improve stability / security / performance. In particular: I understand that a fault or fatal exception in one d...
The basic use case for an AppDomain is in an environment that is hosting 3rd party code, so it will be necessary not just to load assemblies dynamically but also unload them. There is no way to unload an assembly individually. So you have to create a separate AppDomain to house anything that might need to be unloaded. ...
2,207,159
2,209,496
Alternative to Factory Pattern when creating templated objects - C++
I want to implement a Mesh class for a CG project, but have run into some problems. What I want to do is a Mesh class that hides implementation details (like loading to a specific API: OpenGL, DirectX, CUDA, ...) from the user. Additionally, since the Mesh class will be used in research projects, this Mesh class has to...
It's an interesting problem, but let's discuss the compiler error first. As the compiler said, a function cannot be both virtual and template. To understand why, just think about the implementation: most of the times, objects with virtual functions have a virtual table, which stores a pointer to each function. For temp...
2,207,219
2,207,398
How do I define friends in global namespace within another C++ namespace?
I'd like to define a binary operator on in the global namespace. The operator works on a class that is defined in another namespace and the operator should get access to the private members of that class. The problem I have is that I don't know how to scope that global operator when making it a friend in the class defi...
First, note that your operator declaration was lacking a namespace qualification for A: NAME::A operator * (double lhs, const NAME::A& rhs) and then the decisive trick is to add parentheses to the friend declaration like this, just as you proposed in your "pseudo-code" friend A (::operator *) (double lhs, const A& rhs...
2,207,309
11,960,349
Odd optimisation problem under MSVC
I've seen this blog: http://igoro.com/archive/gallery-of-processor-cache-effects/ The "weirdness" in part 7 is what caught my interest. My first thought was "Thats just C# being weird". Its not I wrote the following C++ code. volatile int* p = (volatile int*)_aligned_malloc( sizeof( int ) * 8, 64 ); memset( (void*)p, 0...
Well I had a brief chat with an intel engineer about exactly this problem and got this response: It's clearly something to do with which instructions end up in which execution units, how quickly the machine spots a store-hit-load problem, and how quickly and elegantly it deals with unrolling the speculative exec...
2,207,527
2,207,552
Changing a label in Qt
I'm trying to make a simple program consisting of a button and a label. When the button is pressed, it should change the label text to whatever is in a QString variable inside the program. Here's my code so far: This is my widget.h file: class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent =...
You are connecting the signal to the wrong object. myclicked() is not a slot of QLabel, it is a slot of your Widget class. The connection string should be: connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(myclicked())); Take a look at the console output of your program. There should be an error message saying som...
2,207,628
2,207,640
Calling in C++ a non member function inside a class with a method with the same
I have this class with an instance method named open and need to call a function declared in C also called open. Follows a sample: void SerialPort::open() { if(_open) return; fd = open (_portName.c_str(), O_RDWR | O_NOCTTY ); _open = true; } When I try to compile it (using GCC) I get the following...
Call fd = ::open(_portName.c_str(), O_RDWR | O_NOCTTY ); The double colon (::) before the function name is C++'s scope resolution operator: If the resolution operator is placed in front of the variable name then the global variable is affected.
2,207,852
2,209,397
QtWebkit synchronous loading
I'm using a QWebPage without a QWebView because I want to render the contents of an HTML file onto a QPixmap/QImage. I want the loading of the page to be done synchronously, not asynchronously which is the default. The default way is to call QWebFrame::setHtml() or QWebFrame::setContent(), but this loads images asynch...
If anyone's interested, I implemented this using a special "PageRasterizer" class. The class creates a QWebPage in the constructor and sets a bool loading flag to false. A connect() call connects the loadFinished signal to a member slot that merely sets the loading flag to true. A special RenderPage() member function t...
2,207,881
2,211,255
Using a java socket from JNI / C++ code
I have a java app that creates a socket to talk to a server process, eg new java.net.Socket(String host, int port). This app includes a bunch of legacy c++ code that needs to suck gobs of data from that server and process it. This is currently implemented by having the native code create its own socket and connect to t...
To answer your first question: if it's possible to reuse Java's socket from within the native code -- yes it is possible, but I would not recommend it (you would tie yourself to the internals of a specific implementation/version); but if you really must: use reflection to get access to java.io.FileDescriptor on the jav...
2,208,047
2,208,093
MS Visual Studio Project header files
I am fairly new to developing C/C++ code in MSVS but one of the things that has already confused me is why, after adding a set of source and header files to my project such that they show up respectively under the MSVS folders 'Source Files' and 'Header Files', do I subsequently have to tell the compiler where my heade...
Actually, adding your header files in the so called "Header Files" folder is optional. Even without doing the same you can just specify the header path in "Project->Properties->...." and it will still work. You may be thinking from the perspective of only your project's header files which can be added in the "Header Fi...
2,208,202
2,208,234
C++: Is there a way to define a static array inline?
I would like to define a simple template function which takes a runtime value and determines if it is a member of some set of possible values. Usage: int x; // <- pretend this came from elsewhere... if (isoneof(x, {5,3,9,25}) ... Something like: template <typename T, size_t size> bool isoneof(T value, T (&arr)[size])...
If you like such things, then you will be a very happy user of Boost.Assign. Boost.Assign actually proves that such semantics are possible, however one look at the source of assign will convince you that you don't want to do that by yourself :) You will be able to create something like this however: if (isoneof(x, list...
2,208,246
2,208,279
Using readv(), writev() and poll() from C++
There is a multiplayer card game which I had first programmed as a non-forking socket server in C (using poll() call). Then it was too difficult for me to add new features and I've switched to Perl (using IO::Poll module). As Perl doesn't support readv()/writev(), requires more memory/CPU and also isn't very commercial...
The functions readv(), writev(), and poll() work the same way in C++ as they do in C.
2,208,293
2,208,313
What is the most efficient way to append one std::vector to the end of another?
Let v1 be the target vector, v2 needs to be appended to the back of it. I'm now doing: v1.reserve(v1.size() + v2.size()); copy(v2.begin(), v2.end(), back_inserter(v1)); Is this the most efficient way? Or can it maybe be done just via copying a chunk of memory? Thanks!
After a lot of arguing (and a reasonable comment from Matthieu M. and villintehaspam), I'll change my suggestion to v1.insert( v1.end(), v2.begin(), v2.end() ); I'll keep the former suggestion here: v1.reserve( v1.size() + v2.size() ); v1.insert( v1.end(), v2.begin(), v2.end() ); There are some reasons to do it the ...
2,208,411
2,208,418
easy way to randomize the entries of an array using stl?
I can sort a int* array using stl, plain and simple like std::sort(myarray, myarray + size); Is there any equal simple way to randomize it? thanks
std::random_shuffle(myarray, myarray + size);
2,208,529
2,208,602
"Read-Only Region" Visual Studio 2008 options
Extends In Tools/Options/Environment/Fonts and Colors, If you choose to "Show settings for" Text Editor and look in the Display items dialog it says there' a "Read-Only" region you can set the font for. I'm not sure what's that for? Where do you encounter the read-only regions this dialog wants to set the font for?
According to the help file: Read-Only Region: Code that cannot be edited. For example code displayed in the Code Definition View window or code that cannot be modified during Edit and Continue.
2,208,581
2,208,622
Socket listen doesn't unbind in C++ under linux
I have a socket that listens on some port. I send the SIGSTOP signal to the thread that waits on the port (using accept) and terminate it. then I close the fd of the socket that I waited on. But for the next run of my project it doe's not allow me to listen on that port again. My program is in C++ under linux. What sho...
Did you know that sockets are typically kept in a kind of limbo for a minute or two after you've finished listening on them to prevent communications intended for the previous process coming to yours? It's called the 'TIME_WAIT' state. If you want to override that behaviour use setsockopt to set the SO_REUSEADDR flag ...
2,208,834
2,225,010
Multiple definition of lots of std:: functions when linking
I am trying to integrate some external code into my application. My code was pure C, but the new code is C++, so I simply renamed my C files to .cc and compiled the whole thing with g++. It compiles fine, but I get a crapton of link errors : CMakeFiles/svrt.dir/svrtH_generator.cc.o: In function `operator new(unsigned l...
Finally, I was able to make things compile. I found some hints saying that I should get rid of C-style includes (#include <stdlib.h>) and replace them with C++ style includes (#include <cstdlib>). This made things worse ! Putting the includes back to .h style (and correcting the inconsistencies about that in the exern...
2,209,134
2,214,057
getting started with log4cpp in windows
I need to do logging in a C++ application. After googling for a while, I decided to use log4cpp. is that a safe option to go with, or is there something better out there? How do I get started with installation and importing it to my application using Windows XP, Visual Studio 2005? TIA
I've used Log4cpp in the past and it does the job, though bear in mind the project has been inactive since 2007. There are also the following alternatives: Apache's log4cxx which is still active. Matthew Wilson's Pantheios library. Log4cplus. As for getting started, does the documentation not cover this?
2,209,135
2,209,148
Safely prompt for yes/no with cin
I'm in an intro to C++ class and I was wondering of a better method of checking if input was the desired type. Is this a good way of doing this? I come from a PHP/PERL background which makes me rather apprehensive of using while loops. char type; while (true) { cout << "Were you admitted? [y/n]" << endl; cin >...
Personally I'd go with: do { cout << "Were you admitted? [y/n]" << endl; cin >> type; } while( !cin.fail() && type!='y' && type!='n' );
2,209,224
2,209,233
vector vs. list in STL
I noticed in Effective STL that vector is the type of sequence that should be used by default. What's does it mean? It seems that ignore the efficiency vector can do anything. Could anybody offer me a scenario where vector is not a feasible option but list must be used?
Situations where you want to insert a lot of items into anywhere but the end of a sequence repeatedly. Check out the complexity guarantees for each different type of container: What are the complexity guarantees of the standard containers?
2,209,257
2,209,269
What's the alternate character combination for the double quote character in C/C++?
I've not had the Kernighan and Ritchie C reference in years, but I remember that there was a page in there that talked about how to enter characters that were unavailable to you. (WAY back in the day, some keyboards lacked characters like ", ~, etc.) To be clear, let me give an example. I'm not looking for a way to g...
You are looking for a trigraph for " character? I don't think one exists. Trigraphs don't exist for all characters. Only a few characters have trigraph sequences.
2,209,355
2,209,433
Is using Java the proper language/platform for developing a GUI based accounting app?
I know this is partially subjective, but hopefully with enough specifics I can get a good answer. I am looking to develop an accounting app targeted at a specific market segment (think Quickbooks, but tweaked). Most of the app will be editable tables that are linked with DB data and some basic reporting and graphic fun...
First thing I should say is "there is no right answer here". Java can do exactly what you want. The GUI toolkit, after years of reworking, is very advanced. There are also lots of tools, frameworks, and extensions you can use to make the GUI look very advanced. Java also has a great DB connection framework. With O...
2,209,490
2,209,612
Win32API: How to request embedded windows event notifications out to a parent window
Scenario: I would like a window control which is a sub-window in my dialog (a subwindow of a subwindow) to propagate its notification messages out to the dialog window. e.g. A COMBOBOX contains an EDIT control. I have a circumstance where I would really like to know when the EDIT field gains and loses focus (mainly bec...
I believe you need to subclass the window, see http://msdn.microsoft.com/en-us/library/ms997565.aspx (Content has been removed!) .
2,209,571
2,209,599
Assignment to unions of members
Let's say I have a class with union members in it: class ClassX { public: union { StructA * A; StructB * B; }; } If I have pointers x1 and x2 to different ClassX objects, does this: x1->A = x2->A; Have the same effect as this: x1->B = x2->B; ? Thanks.
For most practical purposes, on most implementations, those two statements would have the same effect, however it's not guaranteed. If the member that you read from a union isn't the last member that was writted to the union the behaviour of the program is undefined. Because both members of the union are pointers to st...
2,209,603
2,209,831
Strange C++ performance difference?
I just stumbled upon a change that seems to have counterintuitive performance ramifications. Can anyone provide a possible explanation for this behavior? Original code: for (int i = 0; i < ct; ++i) { // do some stuff... int iFreq = getFreq(i); double dFreq = iFreq; if (iFreq != 0) { // do som...
You should put the conversion to dFreq immediately inside the if() before doing the calculations with iFreq. The conversion may execute in parallel with the integer calculations if the instruction is farther up in the code. A good compiler might be able to push it farther up, and a not-so-good one may just leave it whe...
2,209,652
2,210,214
Fewer connections in a Qt calculator
I'm writing a simplified calculator using Qt with C++, for learning purposes. Each number is a QPushButton that uses the same slot to modify the text in a lineEdit widget being used as a display. The slot uses the sender() method to figure out which button was pressed, so the correct number would be written on the disp...
If you use QtDesigner or the form editor of QtCreator you can just drag lines between the 2 and it will fill in the code for you. You could also keep all the buttons in a list structure, but I would use a QVector not a standard array. You might also want to reconsider using the sender() method, it violates OOP design. ...
2,209,875
2,210,102
C++: A way to declare a variable (or more than one) in an if statement that separates out the variable definition and the test?
One can do this: case WM_COMMAND: if (WORD wNotifyCode = HIWORD(wparam)) { ... } And one can do this: case WM_COMMAND: { WORD wNotifyCode = HIWORD(wparam); if (wNotifyCode > 1) { ... } } But one cannot do: case WM_COMMAND: if ((WORD wNotifyCode = HIWORD(wparam)) > 1) { ... } Using a for statement here ...
Sometimes readability and maintainability is more important then a line of code saved. IF you need the local variable at all then by all means introduce it explicitly in this case and maybe introduce an additional scope if you want it limited - but you should also consider if maybe you can just live with using the HIWO...
2,209,889
2,210,209
How to use C++ operators within python using boost::python (pyopencv)
I'm using the pyopencv bindings. This python lib uses boost::python to connect to OopenCV. Now I'm trying to use the SURF class but don't know how to handle the class operator in my python code. The C++ class is defined as: void SURF::operator()(const Mat& img, const Mat& mask, vector<KeyPoint>& keypo...
You just call it as if it was a function. If surf_inst is an instance of the SURF class, you would call: newKeyPoints = surf_inst(img, mask, keypoints) The argument keypoints is expected to be a tuple, and img and mask should be an instance of the Mat class. The C++ function modifies its keypoints parameter. The Pytho...
2,209,929
2,224,732
Linking different libraries for Debug and Release builds in Cmake on windows?
So I've got a library I'm compiling and I need to link different third party things in depending on if it's the debug or release build (specifically the release or debug versions of those libraries). Is there an easy way to do this in Cmake? Edit: I should note I'm using visual studio
According to the CMake documentation: target_link_libraries(<target> [lib1 [lib2 [...]]] [[debug|optimized|general] <lib>] ...) A "debug", "optimized", or "general" keyword indicates that the library immediately following it is to be used only for the corresponding build configuration. So you should be able ...
2,209,935
2,209,970
Any gotchas in copy ctor and assignment operator having slightly different semantics?
Please look at the following code and tell me if it's going to cause problems in the future, and if yes, how to avoid them. class Note { int id; std::string text; public: // ... some ctors here... Note(const Note& other) : id(other.id), text(other.text) {} void operator=(const Note& other) // returns ...
If you want semantics that don't match what's expected from the assignment operator, then don't use it. Instead, disable it by declaring a private operator= and define a function with a name that makes clear what's going on, like copyDataFields.
2,209,993
2,210,051
How to properly do threading in C++?
I have a rather large, dynamic sparse matrix object class to write, and I want to make the following happen: one thread to handle placing elements into the matrix, and one to handle reading from the matrix. The only time when these two would conflict would be when they would both want to access the same row/column at ...
If this is your first time to do multi-threading, use the Boost.Threads library. Its semantics (including synchronization mechanisms) are very straightforward and your implementation will be portable. http://www.boost.org/doc/libs/1_42_0/doc/html/thread.html
2,210,118
2,210,540
http proxy javascript injection
I have a simple proxy source in C++. I'm trying to modify it to inject some html content into specific pages. I'v managed to get it working but whenever I inject something, part of the original html gets corrupted. I know for a fact that it's not my string handling functions because I have it printing out the result be...
Chunked Encoding? See RFC 2616, Section 3.6.1.
2,210,234
2,210,275
Search a large file for data in C/C++
I have a log file which has a format of this kind: DATE-TIME ### attribute1 ### attribute2 ###attribute3 I have to search this log file for a input attribute(entered from command line) and output the lines that match the entered attribute. A naive approach may be something like this: scan the entire file line by lin...
You can reduce the size of the hash table by only storing hash values and file offsets in it. If the attributes only have a fixed, relatively small number of values, you are more likely to be able to fit the whole hash table in memory. You assign an id to each possible value of the attribute, and then for each id val...
2,210,279
2,210,350
Manual alternative to message map?
I am trying to create a GUI to display information read from a file. So I will need some number of pushbuttons, text fields, and radio buttons - but I won't know how many I need until run-time. I am using Visual Studio 6.0. My toolset is fairly non-negotiable, so please refrain from suggesting Java, or any C++ toolki...
Once upon a time I did something like this. I allocated a rage of control ids (not used in resource.h). Added controls with these ids dynamically to the page. To handle the event I took over the OnCommand on the Windows and listened for controls with ids in the range I was looking for. (I need to search old code to be ...
2,210,388
2,213,027
Swap method with const members
I want to implement a Swap() method for my class (let's call it A) to make copy-and-swap operator=(). As far as I know, swap method should be implemented by swapping all members of the class, for example: class A { public: void swap(A& rhv) { std::swap(x, rhv.x); std::swap(y, rhv.y); ...
After a good nights sleep I think the best answer is to use a a non-const pointer to a const value -- after all these are the semantics you are trying to capture.
2,210,460
2,210,507
Creating a simple program in C++ for windows. How to build GUI
For a school project, we need to create a fairly simple app using C++ and .NET framework. I only know C++, but we need to produce a working executable file for the project. The prof said we can use WYSIWYG editors for the GUI, but i can't seem to find one in Visual C++. I wanted to code with Visual C++ since i want to ...
1) Download Visual C++ 2008 Express for free here 2) Go to File->New->Windows Form Application. Done! You got the WYSIWYG editors for the GUI. Hope it helps Max
2,210,506
2,210,787
compile SQLite amalgamation for Windows Mobile device
How can I compile the SQLite amalgamation for Windows Mobile device? Then I want to use in a console to run some commands. I've created an empty VS project in C/C++ for Smart Device, then included the existing files into Sources and Headers. When I try to compile I get: Error 1 error LNK2019: unresolved external symb...
The amalgamation file does not contain a main function because it's really just the sqlite library, and not a command-line interface program. You will have to implement the commands yourself and link against the sqlite library.
2,210,837
2,210,911
(Text-Based) Games for C++ practice
I'm currently learning C++ and so I thought it would be a good idea trying to (re)program some "common" text-based games. (Thinking of Hunt the Wumpus, Guess a (pseudo) random number generated by the computer,...) However, I can't find any good sources for such tasks. Which text-based games could be "educating" for me...
I'm trying to remember some of the fun stuff I did way back when in my high school CS class. They're not all games but here it goes: Text based (ASCII) animation - Basically I animated an ASCII dragon coming into the terminal, saying something, and leaving. After "drawing" each frame it was cleared so basically it wa...
2,210,839
2,210,934
Conditional CXX_FLAGS using cmake based on compiler?
I've just started using CMake for some personal and school projects, and I've been stumped by a minor issue. Let's say I'm trying to get a C++ program compiling under multiple compilers (g++, cl, and bcc32 in this case). I have different command line switches for each compiler, and what I was attempting to do was to ba...
There are a bunch of pre-defined CMake variables depending on the compiler you're using: if (MSVC) set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE") set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGSS_GO_HERE") set ( CMAKE_CXX_FLAGS_RELEASE "/RELEASE_FLAGS_GO_HERE" ) endif () if (BORLAND) set ( CMAKE_CXX_FLAGS "/GLOBAL_F...
2,210,928
2,210,949
How I do fibonaci sequence under 1000?
#include <iostream> using namespace std; void main() { int i = 0; while (i < 1000) { int TEMP = i * 2; cout << i << endl; TEMP = i; i = i +1; // ??? } return; } I'm so confused?? :(
First you should check that you understand the definition of the Fibonacci numbers. By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s. You need two variables to remember the ...
2,211,012
2,211,085
Working with enum-like data in C++
I am updating an old piece of C++ code and am stuck on a design issue and need advice on the best course of action. The code handles geometric data. Currently, the code defines many global constants to handle element types: #define TETRAHEDRON 0 #define HEXAHEDRON 1 Each constant has information associated with it t...
Create a base class that contains all of the properties that your objects should support, and a private constructor to set those properties. You don't need derived classes, then: you can use static public objects to create the objects that you want with the desired properties. class TopologyObject { private: ...
2,211,030
2,211,614
failing to compile a project, missing io.h file
I fail to compile a C++ project for mobile device with Windows Mobile (Windows CE-based) operating system and Visual C++ compiler from Visual Studio fails with: Error 1 fatal error C1083: Cannot open include file: 'io.h' EDIT I am trying to compile the SQLite amalgamation, the shell.c file includes the call to thi...
The io.h file is not available in SDKs for Windows CE-based systems like Windows Mobile. In fact, io.h header has never been a part of ISO C nor C++ standards. It defines features that belongs POSIX compatibility layer on Windows NT, but not Windows CE. Due to lack of POSIX features on Windows CE, I developed a small u...
2,211,097
2,211,140
dictionary library in C++
I have to use write a program in which the dictionary should be used to check whether one string is a valid word in it. Is there any dictionary library I could use? If not, how could I construct a dictionary for query? Thanks!
struct Dictionary { Dictionary() { // load _words, here's one possible implementation: std::ifstream input ("/usr/share/dict/words"); for (std::string line; getline(input, line);) { _words.insert(line); } } bool contains(std::string const& word) const { return _words.count(word); } std::s...
2,211,128
2,211,192
Why does g++ generate multiple (weak) similar symbols?
I'm looking at the output of nm -C 0804a86a W ForkMessageHandler::ForkMessageHandler() 0804a86a W ForkMessageHandler::ForkMessageHandler() 0804a6fa T ForkMessageHandler::~ForkMessageHandler() 0804a698 T ForkMessageHandler::~ForkMessageHandler() 0804a698 T ForkMessageHandler::~ForkMessageHandler() 0804a800 W MultiMessa...
Those are the default constructors and automatically generated destructors. They will be generated as weak symbols in every compilation unit that includes the class definition to guarantee that there is at least one available. The reason they are weak is to avoid conflicts in the linking process since the class defini...
2,211,319
2,211,437
Can't get DLL to work on Visual Studio
I've been following the tutorial from msdn and it just doesn't work. First problem I have is that sometimes the .dll and .lib aren't built. Instead I only get .objs. Whenever I build the .dll project, it gives me a popup asking to "please specify the name of the executable file to be used for the debug session". I was ...
firstly your description is mixing managed (.net) things with normal c++ stuff. I assume you are doing normal c++ stuff. DO you own (I mean have the source; are the author) both the DLL and the calling program? If so you should have 2 VS projects one for the DLL and one for the program. You should set the program as th...
2,211,656
2,213,166
validating numerical user input
I am creating a simple CLI calculator tool as an exercise. I need to make sure n1 and n2 are numeric in order for the functions to work; consequently, I would like to make the program quit upon coming across a predetermined non-numeric value. Can anyone give me some direction? Additionally, if anyone can offer any gen...
No need for Boost or writing your own template or forcing yourself to use exceptions vs error codes. cin alone does everything you're asking for. You can test if ( cin ) or if ( ! cin ) to determine success or failure. One failure (eg, a letter in numeric input) will stop cin from accepting any more input. Then call ci...