extern c 和extern c++

// my_c_function.c
//
#include <stdio.h>
#include "my_c_function.h"

void print_hello_from_c() {
    printf("Hello from C!\n");
}
// my_c_function.h

extern "C"
{
        void print_hello_from_c();
}
// my_cpp_code.cpp
//
#include "my_c_function.h"
extern "C" {
   void print_hello_from_c();
}

int main() {
    print_hello_from_c(); // 调用C函数
    return 0;
}
g++ -o  my_c_function.o -c my_c_function.c -I ./
g++ -o  my_cpp_code.o -c my_cpp_code.cpp
g++ my_c_function.o my_cpp_code.o -o my_program

用g++ 编译时,如果my_c_function.h 里面有extern “C” 是c的编译方式, 调用如果不extern "C" 会编译失败

// my_c_function.h

print_hello_from_c 

hfu@CNSH-BLD1:~/program/cplusplus/extern_test$ objdump -t my_c_function.o

my_c_function.o:     file format elf64-x86-64

SYMBOL TABLE:
0000000000000000 l    df *ABS*  0000000000000000 my_c_function.c
0000000000000000 l    d  .text  0000000000000000 .text
0000000000000000 l    d  .data  0000000000000000 .data
0000000000000000 l    d  .bss   0000000000000000 .bss
0000000000000000 l    d  .rodata        0000000000000000 .rodata
0000000000000000 l    d  .note.GNU-stack        0000000000000000 .note.GNU-stack
0000000000000000 l    d  .eh_frame      0000000000000000 .eh_frame
0000000000000000 l    d  .comment       0000000000000000 .comment
0000000000000000 g     F .text  0000000000000013 print_hello_from_c
0000000000000000         *UND*  0000000000000000 _GLOBAL_OFFSET_TABLE_
0000000000000000         *UND*  0000000000000000 puts

如果用 g++ 编译时,如果my_c_function.h 里面没有extern “C” 便是c++ 编译方式

// my_c_function.h

//extern "C"
//{
        void print_hello_from_c();
//}

_Z18print_hello_from_cv 

hfu@CNSH-BLD1:~/program/cplusplus/extern_test$ objdump -t my_c_function.o

my_c_function.o:     file format elf64-x86-64

SYMBOL TABLE:
0000000000000000 l    df *ABS*  0000000000000000 my_c_function.c
0000000000000000 l    d  .text  0000000000000000 .text
0000000000000000 l    d  .data  0000000000000000 .data
0000000000000000 l    d  .bss   0000000000000000 .bss
0000000000000000 l    d  .rodata        0000000000000000 .rodata
0000000000000000 l    d  .note.GNU-stack        0000000000000000 .note.GNU-stack
0000000000000000 l    d  .eh_frame      0000000000000000 .eh_frame
0000000000000000 l    d  .comment       0000000000000000 .comment
0000000000000000 g     F .text  0000000000000013 _Z18print_hello_from_cv
0000000000000000         *UND*  0000000000000000 _GLOBAL_OFFSET_TABLE_
0000000000000000         *UND*  0000000000000000 puts

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值