WaciX
WaciX

Reputation: 53

C++11 code/library in non C++11 program

Assume that I compile the code in C++11 (I'll use Lambdas) to ".o" or library ".a". And I have a program, where I will include previous library and header file, that I can't compile with C++11, but old one ( C++98 ). Will it compile and work fine?

Upvotes: 4

Views: 483

Answers (3)

Adrian
Adrian

Reputation: 10911

Probably not. The reason that name mangling (why the ABI changes) in c++ exists is because incompatibility differences between c++ versions can make code unstable if it will work at all.

If you have code that doesn't compile against c++11, you'll probably have to refactor one of your programs to compile against the other compiler. (Most likely get your old code to compile with the new compiler)

If this isn't an option, you can try and make the c++11 lib a DLL with a C interface or with a COM object interface, but exceptions would stop at that boundary, and if you go the DLL route, you would more than likely want to write a wrapper class to access the c++11 object, so that it acts like an object on your pre c++11 side of the boundary.

Upvotes: 3

Richard Cook
Richard Cook

Reputation: 33089

One common approach is to provide a C version of the API (extern "C" functions) with objects passed around using opaque pointers. This is more likely to be compatible between languages and compilers.

Upvotes: 2

Useless
Useless

Reputation: 67733

It will work fine if:

  1. the (public) header doesn't use any C++11 features
  2. the ABI hasn't changed
    • consult your platform/compiler on this one
  3. no common dependency has changed
    • as per the GCC document linked by Vaughn Cato, this includes the standard library. Anything that generates different code or object layouts when compiled with C++11, and is used by both library and client may be a problem ... even if it isn't used in the interface itself.

If point 3 is your only issue, you may be able to get around it by compiling a dynamic library (depending on platform a .so, or a .dynlib, or a DLL as Adrian suggests) with all dependencies statically linked internally and not exported. It's a bit hairy though.

Upvotes: 3

Related Questions