Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different C++ Class Declarations

I'm trying to use a third party C++ library that isn't using namespaces and is causing symbol conflicts. The conflicting symbols are for classes my code isn't utilizing, so I was considering creating custom header files for the third party library where the class declarations only include the public members my code is using, leaving out any members that use the conflicting classes. Basically creating an interface.

I have three questions:

  1. If the compilation to .obj files works, will this technique still cause symbol conflicts when I get to linking?

  2. If that isn't a problem, will the varying class declarations cause problems when linking? For example, does the linker verify that the declaration of a class used by each .obj file has the same number of members?

  3. If neither of those are a problem and I'm able to link the .obj files, will it cause problems when invoking methods? I don't know exactly how C++ works under the hood, but if it uses indexes to point to class methods, and those indexes were different from one .obj file to another, I'm guessing this approach would blow up at runtime.

like image 757
silentorb Avatar asked Sep 30 '22 10:09

silentorb


1 Answers

In theory, you need identical declarations for this to work.

In practice, you will definitely need to make sure your declarations contain:

  • All the methods you use
  • All the virtual methods, used or not.
  • All the data members

You need all these in the right order of declaration too.

You might get away with faking the data members, but would need to make sure you put in stubs that had the same size.

If you do not do all this, you will not get the same object layout and even if a link works it will fail badly and quickly at run-time.

If you do this, it still seems risky to me and as a worst case may appear to work but have odd run time failures.

"if it uses indexes ": To some extent exactly how virtual functions work is implementation defined, but typically it does use an index into a virtual function table.

What you might be able to do is to:

  • Take the original headers
  • Keep the full declarations for the classes you use
  • Stub out the classes and declarations you do not use but are referenced by the ones you do.
  • Remove all the types not referenced at all.
like image 115
Keith Avatar answered Oct 03 '22 01:10

Keith