Calling C++ functions from C file

前端 未结 2 547
抹茶落季
抹茶落季 2020-12-14 04:29

I am quite new to C and C++. But I have some C++ functions which I need to call them from C. I made an example of what I need to do


main.c:

相关标签:
2条回答
  • 2020-12-14 05:07

    the extern "C" tells C++ that the declared function has to use the C ABI (Application Binary interface), hence, whether the language is C or C++, your void HelloWorld() is always seen externally as it is C.

    But you implemented it in the cpp file like it is a C++ one, C is not aware of.

    You have to make the prototype of HelloWorld coherent for both C and C++, so the cpp file should declare it as extern "C" void Helloworld() { /*your code here*/ }, or simply, #include "example.h" from example.cpp, so that, before implementing it, the compiler already knows it has to follow the C convention.

    0 讨论(0)
  • 2020-12-14 05:11

    Short answer:

    example.cpp should include example.h.

    Longer answer:

    When you declare a function in C++, it has C++ linkage and calling conventions. (In practice the most important feature of this is name mangling - the process by which a C++ compiler alters the name of a symbol so that you can have functions with the same name that vary in parameter types.) extern "C" (present in your header file) is your way around it - it specifies that this is a C function, callable from C code, eg. not mangled.

    You have extern "C" in your header file, which is a good start, but your C++ file is not including it and does not have extern "C" in the declaration, so it doesn't know to compile it as a C function.

    0 讨论(0)
提交回复
热议问题