File struct Base|       Foo |           | Foo.hpp &amp; Foo.cpp        Bar |           | Bar.hpp &amp; Bar.cpp        main.cpp &amp; CMakeLists.txt  Bar.hpp template &lt;typename Ty&gt; class Bar { public:     float Value() const; };      Bar.cpp #include &quot;Bar.hpp&quot; template&lt;typename Ty&gt; float Bar&lt;Ty&gt;::Value() const {     return 1234.0; }  Foo.hpp #include &quot;../Bar/Bar.hpp&quot; class Foo : public Bar&lt;int&gt; { public:     float Get() const; };  Foo.cpp #include &quot;Foo.hpp&quot; float Foo::Get() const {     return Value(); }  the main part of CMakeLists.txt add_library(Bar_lib Bar/Bar.cpp Bar/Bar.hpp) add_library(Foo_lib Foo/Foo.cpp Foo/Foo.hpp) target_link_libraries(Foo_lib Bar_lib) add_executable(testing main.cpp) target_link_libraries(testing Foo_lib)  The main.cpp file just calls foo.Get(), and when I run cmake&amp;make it gives /usr/bin/ld: libFoo_lib.a(Foo.cpp.o): in function `Foo::Get() const': Foo/Foo.cpp: undefined reference to `Bar&lt;int&gt;::Value() const'  But when I put everything into main.cpp file, it will successfully compile. So I know it has something to do with make. My question is how can I modify the CMakeLists.txt or even the cpp file to get this thing run? I'm a noob in cmake, so I'm sorry if I asked a dumb question. Big thanks to every suggestion
341
Quote from :     The only portable way of using templates at the moment is to implement them in header files by using inline functions.   Why is this?  (Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)
36051
class Test {        bool isVal() const {           return isVal;       }    private:        bool isVal; };   On Compiling this file it says      testClass.cpp:9: declaration of `bool   Test::isVal'      testClass.cpp:3: conflicts with   previous declaration `bool   Test::isVal()'   Although the same would work for java   class Test {    private boolean isVal;    public boolean isVal() {       return isVal;   }  }   Why does the compile error occur in C++ not in Java?
24839
class Outer {      class Inner {     public:         Inner() {}         void func() ;     };  private:     static const char* const MYCONST;     int var; };  void Outer::Inner::func() {     var = 1; }  const char* const Outer::MYCONST = "myconst";   This errors out when I compile with class Outer::Inner' has no member named `var'
48897
I have a C++ library that provides various classes for managing data.  I have the source code for the library.  I want to extend the C++ API to support C function calls so that the library can be used with C code and C++ code at the same time.  I'm using GNU tool chain (gcc, glibc, etc), so language and architecture support are not an issue.  Are there any reasons why this is technically not possible?  Are there any gotcha's that I need to watch out for?  Are there resources, example code and/or documentation available regarding this?    Some other things that I have found out:   Use the following to wrap your C++ headers that need to be used by C code.     #ifdef __cplusplus extern "C" {   #endif   //   // Code goes here ...   //   #ifdef __cplusplus   } // extern "C"   #endif    Keep "real" C++ interfaces in separate header files that are not included by C.  Think  here.  Using #ifndef __cplusplus #error stuff helps here to detect any craziness. Careful of C++ identifiers as names in C code Enums varying in size between C and C++ compilers.  Probably not an issue if you're using GNU tool chain, but still, be careful. For structs follow the following form so that C does not get confused.  typedef struct X { ... } X  Then use pointers for passing around C++ objects, they just have to be declared in C as struct X where X is the C++ object.   All of this is courtesy of a friend who's a wizard at C++.
65547
See also      Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.  #include &lt;map&gt;  struct MyClass {     MyClass(int t); };  int main() {     std::map&lt;int, MyClass&gt; myMap;     myMap[14] = MyClass(42); }   This gives me the following g++ error:     /usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’   This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax.
97800
When I run a process that links to a shared library at runtime (linked when the process starts, not linked later with dlload()), where does it look for that shared library (.so) file other than LD_LIBRARY_PATH?  Background:  I have some C++ code that I wrote that uses a particular third-party library. I have installed the library and compiled my code on two different platforms, both Ubuntu but different versions, and different versions of gcc as well. The library was compiled and installed from source, and is located in /usr/local/lib on both platforms. When I compile my code, I link with the pkg-config --libs parameters for the third-party library and I've verified that pkg-config --libs returns the exact same thing on both platforms.  My code compiles successfully on both platforms, and LD_LIBRARY_PATH is not defined (or defined as empty: "") on both platforms. However, when I run it on one platoform it works fine, and on the other I get this error:  error while loading shared libraries: libthrift-0.9.0.so: cannot open shared object file: No such file or directory   Funnily enough, the ones that doesn't work is the newer version of Ubuntu and gcc.  :/  So I'm trying to figure out how the working one is able to locate the library, so that I can make the broken one locate the library in the same way. (i.e., without setting LD_LIBRARY_PATH)  Update:  Here's my output from cat /etc/ld.so.conf.d/*  ...on the working (older) system:  /usr/lib/mesa /usr/lib32/mesa /usr/lib/alsa-lib # libc default configuration /usr/local/lib # Multiarch support /lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu   ...on the broken (newer) system:  # libc default configuration /usr/local/lib # Multiarch support /lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/mesa
29293
Say I have classes Foo and Bar set up like this:  class Foo { public:     int x;      virtual void printStuff()     {         std::cout &lt;&lt; x &lt;&lt; std::endl;     } };  class Bar : public Foo { public:     int y;      void printStuff()     {         // I would like to call Foo.printStuff() here...         std::cout &lt;&lt; y &lt;&lt; std::endl;     } };   As annotated in the code, I'd like to be able to call the base class's function that I'm overriding. In Java there's the super.funcname() syntax. Is this possible in C++?
78860
The question was about plain  functions, not  static methods, as clarified in comments.  I understand what a static variable is, but what is a static function?  And why is it that if I declare a function, let's say void print_matrix, in let's say a.c (WITHOUT a.h) and include "a.c" -  I get "print_matrix@@....) already defined in a.obj", BUT if I declare it as static void print_matrix then it compiles?  UPDATE Just to clear things up - I know that including .c is bad, as many of you pointed out. I just do it to temporarily clear space in main.c until I have a better idea of how to group all those functions into proper .h and .c files. Just a temporary, quick solution.
45776
I'm trying to do something like the following:  enum E;  void Foo(E e);  enum E {A, B, C};   which the compiler rejects.  I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why.  Can anyone explain?  Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as  enum E {     FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X }   as project X is not something I want my users to know about.  So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.  As for the compiler - it's GCC.
12470
Why do we need to use:  extern "C" { #include &lt;foo.h&gt; }   Specifically:     When should we use it? What is happening at the compiler/linker level that requires us to use it?   How in terms of compilation/linking does this solve the problems which require us to use it?
69649
I'm using GCC; __FILE__ returns the current source file's entire path and name: /path/to/file.cpp. Is there a way to get just the file's name file.cpp (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings?  I am using this in an error logging macro. I really do not want my source's full path making its way into the executable.
113468
I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred.  Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to_str() member function for A.  In pseudocode:  class A { public:   ...    void print(FILE* f);   B b;    ...   };  ...  void A::print(FILE *f) {   std::string s = "stuff";   fprintf(f, "some %s", s);   b.print(f); }  class C {   ...   std::string foo;   bool set_foo(std::str);   ... }  ...  A a = new A(); C c = new C();  ...  // wish i knew how to write A's to_str() c.set_foo(a.to_str());   I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE* F) interface also needs to be preserved. I have considered several approaches to implementing A::to_str(), each with advantages and disadvantages:   Change the calls to fprintf() to sprintf()   I wouldn't have to rewrite any format strings print() could be reimplemented as: fprint(f, this.to_str()); But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string  Try to catch the results of a.print() in a string stream   I would have to convert all of the format strings to &lt;&lt; output format. There are hundreds of fprintf()s to convert :-{ print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though ).  Use Boost's string    More external dependencies. Yuck. Format's syntax is different enough from printf() to be annoying:    printf(format_str, args) -> cout &lt;&lt; boost::format(format_str) % arg1 % arg2 % etc Use Qt's    A different external dependency.    So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?  Thanks.
14677
I would like to call python script files from my c++ program.   I am not sure that the people I will distribute to will have python installed.  Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.
93897
If I have a template function, for example like this:  template&lt;typename T&gt; void func(const std::vector&lt;T&gt;&amp; v)   Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:  template&lt;typename T&gt; void func(const std::vector&lt;T*&gt;&amp; v)   Thanks
7923
template&lt;typename T, size_t n&gt; size_t array_size(const T (&amp;)[n]) {     return n; }   The part that I don't get is the parameters for this template function. What happens with the array when I pass it through there that gives n as the number of elements in the array?
30635
I'm a C++ newbie, but I wasn't able to find the answer to this (most likely trivial) question online.  I am having some trouble compiling some code where two classes include each other.  To begin, should my #include statements go inside or outside of my macros?  In practice, this hasn't seemed to matter.  However, in this particular case, I am having trouble.  Putting the #include statements outside of the macros causes the compiler to recurse and gives me "#include nested too deeply" errors.  This seems to makes sense to me since neither class has been fully defined before #include has been invoked.  However, strangely, when I try to put them inside, I am unable to declare a type of one of the classes, for it is not recognized.  Here is, in essence, what I'm trying to compile:  A.h  #ifndef A_H_ #define A_H_  #include "B.h"  class A {     private:         B b;      public:         A() : b(*this) {} };  #endif /*A_H_*/   B.h  #ifndef B_H_ #define B_H_  #include "A.h"  class B {     private:             A&amp; a;      public:         B(A&amp; a) : a(a) {}  };  #endif /*B_H_*/   main.cpp  #include "A.h"  int main() {     A a; }   If it makes a difference, I am using g++ 4.3.2.  And just to be clear, in general, where should #include statements go?  I have always seen them go outside of the macros, but the scenario I described clearly seems to break this principle.  Thanks to any helpers in advance!  Please allow me to clarify my intent if I have made any silly mistakes!
21478
I have a c++ header file containing a class. I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file:     // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{  class TestClass{ public:     void testMethod(); };  void TestClass::testMethod(){     // some code here... }  } // end namespace test_ns #endif   If inside the same project I include this header from more than one cpp file, I get an error saying "multiple definition of test_ns::TestClass::testMethod()", while if I put the method definition inside the class body this does not happen:  // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{  class TestClass{ public:     void testMethod(){         // some code here...     } };  } // end namespace test_ns #endif   Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?