C和C++相互调用

C和C++几乎是不分仲伯,我们在写C代码或是C++代码时,常常会发生彼此混合调用的现象;而且C语言和C++语言都有一些独有的非常有价值的项目,因而两种语言的互操作,充分利用前人造的轮子是一件非常有价值的事情。

  • C++调用C代码

  1.  C++中相关的定义及声明

    #ifdef __cplusplus
    extern "C" {
    #endif // __cplusplus
    
    #include <stdio.h>
               void show();
    #ifdef __cplusplus
    }          
    #endif
    
    int main(int argc, char *argv[])
    {
        show();
        return 0;
    }
  2. C代码中被调用函数的实现 

    C头文件 

    
    /*c头文件*/
    #ifndef __TEST_H__ 
    #define __TEST_H__ 
    
    void show();
    
    #endif
    

    C源文件

     

    
    /*c源文件文件*/
    #include "c_test.h"
    #include <stdio.h>
    
    void  show()
    {
        printf("show in c is:%s\n", "Hello Word");
    }
  3. makefile文件

    cpp:
        gcc -c *.c
        g++ -c *.cpp 
        g++ -o cpp_test *.o
    
    clean:
        rm *.o cpp_test
  4. 编译及运行结果 

     

  •  C代码调用C++代码

  1. C++中相关的定义及声明

    C++头文件

    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
        void cpp_fun();
    
    #ifdef __cplusplus
    }
    #endif

    C++源文件

    
    #include "cpp_test.h"
    #include <stdio.h>
    
    #ifdef __cplusplus
    extern "C"
    {
    #endif
    
        void cpp_fun()
        {
                printf("cpp_fun :%s\n","Hello Word C");
        }
    
    #ifdef __cplusplus
    }
    #endif
  2. C代码中被调用函数的实现 
    
    #include "cpp_test.h"
    
    int main()
    {
            cpp_fun();
    }        
  3.  makefille文件

    c:
            gcc -c *.c
            g++ -c *.cpp 
            gcc -o c_test *.o -lstdc++
    clean:
            rm *.o c_test 
  4. 编译及运行结果 

     

发布了49 篇原创文章 · 获赞 40 · 访问量 4706

猜你喜欢

转载自blog.csdn.net/qq_44045338/article/details/105746744