开发者

c files inside a c++ program

#include <iostream>
#include <string>
#include <vector>

extern "C"{
#include "sql.c"
}

class ReportsSync{

    public:
        string getQuery(开发者_JAVA百科);                     
        bool testQuery(string);        
};

if i have a cpp file like tis, rather a .h file like this, wud i be able to call functions defines in sql.c as usual, like i am calling c++ functions? for eg: if sql.c has a function named foo, which returns a datatype defines in sql.c itself, can i use the returned datatype inside maybe the testQuery(), manipulate it or give it to the next function?


For #include directives the preprocessor does just a text replacement. It is like you copy all text from sql.c to your source file.

So yes you can call the functions defined in sql.c.

The only thing I know of where care is required is if your C functions take function pointers as parameters to provide a callback. You should not throw exceptions in such a callback because C does not know about C++ exceptions.

However as already pointed out in the comments it is more common to #include header files. So you can use the functions of sql.h in more than one compilation unit (.c file).


Just one thing (too large to put in a comment).

Adding extern "C" { <SOMETHING> } to a C++ source does not automagically make that SOMETHING C. It is still C++, but the interface from that SOMETHING follows C rules instead of C++ rules.

#ifndef __cplusplus

/* plain old C */
int y(void) {
  return sizeof 'a';
}

#else

/* C++ */
#include <iostream>

extern "C" {
  int y(); /* y is defined above, compiled with a C compiler */
  int x() {
    return sizeof 'a';
  }
}

int main() {
  std::cout << "regular sizeof 'a' is " << sizeof 'a' << std::endl;
  std::cout << "extern \"C\" sizeof 'a' is " << x() << std::endl;
  std::cout << "plain old C sizeof 'a' is " << y() << std::endl;
}
#endif

Compilation for the program above saved as "c++c.src" and test run

$ gcc -std=c89 -pedantic -c -xc c++c.src -o y.o
$ g++ y.o -pedantic -xc++ c++c.src
$ ./a.out
regular sizeof 'a' is 1
extern "C" sizeof 'a' is 1
plain old C sizeof 'a' is 4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜