extern “C” 的使用

關於 extern “C”,我只寫實踐,簡單易懂。

用於:C++ 需要用到C的庫和 .o文件 ,纔會用到,注意是 ‘庫’(動態庫,靜態庫)。

注意:C++ 和.C 文件直接可以g++,但不能gcc。


例: hello.c

#include <stdio.h>
void hello(void);
{
    printf("Hello");
}

    myhello.cxx

#include <stdio.h>
void hello(void);
int main(void)
{
    hello();
    
    return 0;
}

使用:1.g++ myhello.cxx hello.c

    

    myhello2.cxx

#include <stdio.h>
extern "C" void hello(void);
int main(void)
{
    hello();
    
    return 0;
}


使用方法:

    1.gcc -c hello.c

    2.g++ myhello2.cxx hello.o


分析:

    gcc 編譯 函數hello,生成 hello;

    g++ 編譯 函數hello,生成 hello_init 等,與編譯器gcc 不同,所以不加關鍵字會出錯誤:沒有聲明,C++中加入 extern “C”,按gcc 編譯,就是hello,可以找到函數。   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章