我有一个C++函数,在.h文件中定义,.cpp文件中实现如下:
extern "C" void func(bool first, float min, float* state[6], float* err[6][6])
{
//uses vectors and classes and other C++ constructs
}
我该如何在C文件中调用函数?我应该如何设置文件结构/Makefile以编译它?谢谢!
您可以按照普通方式从C中调用该函数。 但是,您需要将extern "C"
包装在预处理器宏中,以防止C编译器看到它:
您可以正常地从C中调用该函数。不过,为了防止C编译器看到extern "C"
,您需要将其包装在预处理器宏中:
#ifndef __cplusplus
extern "C"
#endif
void func(bool first, float min, float* state[6], float* err[6][6]);
假设您正在使用GCC,则使用gcc
编译C代码,使用g++
编译C ++代码,然后使用g++
链接。
.so
、.dll
等)。因为这是GCC,我认为它可能是Linux,即使不是,其他平台上的GCC仍然使用.so
。(Mac无论如何都使用它,在Windows上需要类似Cygwin的层)。 - Linuxios#ifdef __cplusplus
吗? - Osman-pasha要在C语言中调用它,你只需要正常调用即可。因为你使用了extern "C"
告诉编译器使用C语言的调用约定和ABI,所以你可以正常地调用它:
func(args);
要编译,请使用以下代码进行C++:
g++ -c -o myfunc.o myfunc.cpp
gcc -c -o main.o somec.c
以下是链接:
g++ -o main main.o myfunc.o
确保函数的 C++ 头文件仅使用 C 构造。因此,请在 .cpp
文件中包含诸如 <vector>
等内容。
-c
选项告诉编译器仅将您的代码编译为中间目标代码文件(.o
),然后通过排除 -c
选项将它们链接在一起形成可执行文件。目标文件允许您结合 C 和 C++,并将项目的不同部分分开。 它们还允许您仅编译代码的小部分,这对于像 make 的大型项目和系统至关重要。 - Linuxios使用C语言调用它:
func(/* put arguments here */);
//header file included from both C and C++ files
#ifndef __cplusplus
#include <stdbool.h> // for C99 type bool
#endif
#ifdef __cplusplus
extern "C" {
#endif
void func(bool first, float min, float* state[6], float* err[6][6]);
#ifdef __cplusplus
} // extern "C"
#endif
// cpp file
#include "the_above_header.h"
#include <vector>
extern "C" void func(bool first, float min, float* state[6], float* err[6][6]);
{
//uses vectors and classes and other C++ constructs
}
// c file
#include "the_above_header.h"
int main() {
bool b;
float f;
float *s[6];
float *err[6][6];
func(b,f,s,err);
}
{ }
之间的部分)或者是在头文件中声明(即以);
结尾)?如果是前者,您需要编写另一个头文件,省略extern "C"
和{ }
这两部分,然后将其用于程序的C部分。 - DevSolar