title: How to call a c++ class and its method from a c file
body: <p>I am trying to access a C++ class and call its method from a <code>.c</code> file.</p>
  
  <p>I google this topic and find this <a href="http://developers.sun.com/solaris/articles/mixing.html" rel="nofollow noreferrer">http://developers.sun.com/solaris/articles/mixing.html</a></p>
  
  <p>It says:</p>
  
  <blockquote>
    <p>You can write <code>extern "C"</code> functions in C++ that access class <code>M</code> objects and call them from C code.</p>
  </blockquote>
  
  <p><strong>Here is a C++ function designed to call the member function <code>foo</code>:</strong></p>
  
  <pre><code>extern "C" int call_M_foo(M* m, int i) { return m-&gt;foo(i); }
  </code></pre>
  
  <p>My question is where do I put the about line? In my C++ <code>.h</code> file? Or C <code>.h</code> file?</p>
  
  <p>And it goes on and says:</p>
  
  <p><strong>Here is an example of C code that uses class <code>M</code>:</strong></p>
  
  <pre><code>struct M;                       // you can supply only an incomplete declaration
  
  int call_M_foo(struct M*, int); // declare the wrapper function
  
  int f(struct M* p, int j)       // now you can call M::foo
  {
    return call_M_foo(p, j);
  }
  </code></pre>
  
  <p>But how/where do I create the class <code>M</code> in my C file? 
  And where do I put the above code? C <code>.h</code> file? C++ <code>.h</code> file? Or C <code>.c</code> file?</p>
  
  <p>Thank you.</p>
  
  <p>Thank you for <strong>GMan</strong>'s detailed answer.
  I did follow your suggestion. But I get compile error in my <code>.c</code> file.</p>
  
  <blockquote>
    <p>main.c:33:<br>
    ./some_class.h:24: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or  ‘<strong>attribute</strong>’ before ‘<em>’ token<br>
    ./some_class.h:25: error: expected ‘)’ before ‘</em>’ token<br>
    ./some_class.h:26: error: expected ‘)’ before ‘*’ token</p>
  </blockquote>
  
  <p>And here are my <code>some_class.h</code> line <code>24-26</code>:</p>
  
  <pre><code>#ifdef __cplusplus 
  class M {
  
  public:
    M();
    virtual ~M(); 
  
    void method1(char* name, char* msg);
  };
  
  extern "C" {
  #else
  struct M;
  #endif
  
    /* access functions line 24-26 are here*/ 
    M* M_new(void);
    void M_delete(M*);
    void M_method1(M*, char*, char*);
  #ifdef __cplusplus 
  }
  #endif
  </code></pre>
  
  <p>For some reason, my C compiler does not like <code>extern "C"</code> in <strong>GMan</strong>'s original <code>some_test.h</code>. So I have to modify to above. It seems like the C compiler does not like/understand the <code>struct M;</code> line.</p>
  
  <p>Any idea will be much appreciated.</p>