Topic: Extern "C" {} & class forward declarations


Author: gnb@bby.com.au (Gregory Bond)
Date: 1996/02/19
Raw View
I'm trying to write a C++ wrapper around a C struct+functions that is
more-or-less an object.  But I am having problems that seem to me to
have no standard-conforming solution.

Because the C header file is large and full of lots of irrelevent
details I am trying to hide, the wrapper class has a pointer to the C
struct and the C struct is forward-declared.  The implementation of
the object naturally has to include the C header.

I can find (in the jan96 dwp) no notion of how linkage-specs's apply
to _types_ - 7.5 [dcl.link] only explicitly refers to _objects_ and
_functions_.

To concretise the discussion:
-- thing.h --
/* A C header */
typedef struct {} thing;
/* Bunch of functions that operate on thing *'s */
--
-- Thing.H --
// C++ Wrapper object
class thing;
class Thing {
private:
 thing *_o;
public:
// bunch of member functions
};
--

Now, how do I implement Thing.C in a conforming manner?  If I do
this:
-- Thing.C --
#include "Thing.H"
extern "C" {
#include "thing.h"
}
--
then the compiler complains that "thing" is redeclared - once with
(implicit) C++ linkage, once with C linkage.  This is as it should be
if "thing" were an object or function: see dwp 7.5.3.

If I do this:
-- Thing.C --
extern "C" {
#include "thing.h"
}
#include "Thing.H"
--
then it compiles & runs OK, but by the one-definition-rule we have a
non-conforming program because the linkage of the type "thing" is
different in Thing.C to the rest of the program.

I tried wrapping the forward-dec of thing in the Thing.H header in
extern "C" {}, but my compiler (g++ 2.7.2) seems to ignore the linkage
of forward-declared classes (which seems reasonable) and I get the
same double-definition error.

So it seems I am stuck.  I can include the full C header in the Thing.H
header, which exposes all the stuff I was trying to hide.  Or I grin
and bear it and live with violating the ODR and hope it never jumps up
and bites me.

Or the standard adds some sort of caveat to either the link spec or ODR to
explicitly make one or other of these solutions legal.....

Or (of couse) I missed something!

Greg.
--
Gregory Bond <gnb@bby.com.au> Burdett Buckeridge & Young Ltd Melbourne Australi
a
``Efforts to maintain the "purity" of a language only succeed in establishing
  an elite class of people who know the shibboleths.  Ordinary folks know
  better, even if they don't know what "shibboleth" means.'' - Larry Wall
---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  Moderation policy:
  http://reality.sgi.com/employees/austern_mti/std-c++/policy.html. ]