C语言中 extern "C"使用

来源:互联网 发布:淘宝收不到卖家消息 编辑:程序博客网 时间:2024/06/05 20:25

作用:实现C++与C语言的互通性。
一、标准头文件的结构
#ifndef __INCvxWorksh
#define __INCvxWorksh 
#ifdef __cplusplus   /*如果采用了C++,如下代码使用C编译器;__cplusplus是cpp中的自定义宏,那么定义了这个宏的话表示这是一段cpp的代码,也就是说,上面的代码的含义是:如果这是一段cpp的代码,那么加入extern "C"{}处理其中的代码。*/
extern "C" {       //如果没有采用C++,顺序预编译
#endif 
/*...*/             /*代码段*/ /*采用C编译器编译的C语言代码段*/
#ifdef __cplusplus  /*结束使用C编译器*/
}
#endif         
#endif /* __INCvxWorksh */
注释:头文件中的编译宏“#ifndef __INCvxWorksh、#define __INCvxWorksh、#endif” 的作用是防止该头文件被重复引用。
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
注释:extern用于表示全局范围,对应的static表示局部的范围,限本文件使用。
二、(1)C++中调用C语言中的变量或者函数
C语言头文件中声明如下:
#ifdef  __cplusplus
extern "C" {
#endif
 
/**** some declaration or so *****/
 
#ifdef  __cplusplus
    }
#endif  /* end of __cplusplus */
例子:test_extern_c.h
/* file: test_extern_c.h */
#ifndef __TEST_EXTERN_C_H__
#define __TEST_EXTERN_C_H__
 
#ifdef  __cplusplus
extern "C" {
#endif
 
/*
 * this is a test function, which calculate
 * the multiply of a and b.
 */
extern int ThisIsTest(int a, int b);
 
#ifdef  __cplusplus
    }
#endif  /* end of __cplusplus */
 
#endif
c语言源文件
/* test_extern_c.c */
#include "test_extern_c.h"
 
intThisIsTest(int a, int b)
{
    return (a + b);
}
C++源文件:(调用C语言中函数)
/* main.cpp */
#include "test_extern_c.h"
#include <stdio.h>
#include <stdlib.h>
 
class FOO {
    public:
        int bar(int a, int b)
        {
            printf("result=%i\n", ThisIsTest(a, b));
        }
};
 
intmain(int argc, char **argv)
{
    int a = atoi(argv[1]);
    int b = atoi(argv[2]);
 
    FOO *foo = new FOO();
    foo->bar(a, b);
    return(0);
}
编译:
[cyc@cyc src]$ gcc -c test_extern_c.c

[cyc@cyc src]$ g++ main.cpp test_extern_c.o

[cyc@cyc src]$ ./a.out 4 5

注释:C语言中不支持extern "C"声明,在.c文件中包含了extern "C"时会出现编译语法错误。
例子:C++引用C函数例子工程中包含的三个文件的源代码如下:
/* c语言头文件:cExample.h */
#ifndef C_EXAMPLE_H
#define C_EXAMPLE_H
extern int add(int x,int y);
#endif
/* c语言实现文件:cExample.c */
#include "cExample.h"
int add( int x, int y )
{
return x + y;
}
// c++实现文件,调用add:cppFile.cpp
extern "C"
{
#include "cExample.c"
}
int main(int argc, char* argv[])
{
add(2,3);
return 0;
}
(2)C语言中调用C++文件中的函数,C引用C++函数例子源代码如下:
注意:在C语言中不能直接引用声明了extern "C"的该头文件,应该仅将C文件中将C++中定义的extern "C"函数声明为extern类型。
//C++头文件 cppExample.h
#ifndef CPP_EXAMPLE_H
#define CPP_EXAMPLE_H
extern "C" int add( int x, int y );
#endif
//C++实现文件 cppExample.cpp
#include "cppExample.h"
int add( int x, int y )
{
return x + y;
}
/* C实现文件 cFile.c
/* 这样会编译出错:#include "cExample.h" */
extern int add( int x, int y );
int main( int argc, char* argv[] )
{
add( 2, 3 ); 
return 0;
}
参考资料1
参考资料2
 


0 0