How do I call a C function from C++?

Just declare the C function ``extern "C"'' (in your C++ code) and call it (from your C or C++ code). For example: // C++ code

        extern "C" void f(int); // one way
        extern "C" { // another way
            int g(double);
           double h();
        };
        void code(int i, double d)
        {
              f(i);
              int ii = g(d);
             double dd = h();
             // ...
        }
The definitions of the functions may look like this: /* C code: */
        void f(int i)
        {
              /* ... */
        }
        int g(double d)
       {
             /* ... */
       }
       double h()
      {
            /* ... */
      }
Note that C++ type rules, not C rules, are used. So you can't call function declared ``extern "C"'' with the wrong number of argument. For example: // C++ code
        void more_code(int i, double d)
        {
               double dd = h(i,d); // error: unexpected arguments
               // ...
       }

No comments:

Post a Comment