extern c 和extern c++

cpp 复制代码
// my_c_function.c
//
#include <stdio.h>
#include "my_c_function.h"

void print_hello_from_c() {
    printf("Hello from C!\n");
}
cpp 复制代码
// my_c_function.h

extern "C"
{
        void print_hello_from_c();
}
cpp 复制代码
// 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;
}
bash 复制代码
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

bash 复制代码
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++ 编译方式

cpp 复制代码
// my_c_function.h

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

_Z18print_hello_from_cv

bash 复制代码
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
相关推荐
White の algo6 分钟前
【C++初阶】内存管理
开发语言·c++
iuhart12 分钟前
Golang中的 “...” 操作符
开发语言·golang
敖行客 Allthinker15 分钟前
Go 语言中 panic 和 recover 的代价:性能与设计的权衡
开发语言·后端·golang
osir.1 小时前
2025天梯训练1
c++·多关键字最短路
Zach_yuan1 小时前
list的模拟实现
c++·list
胡桃不是夹子1 小时前
学会了蛇形矩阵
c++·算法·矩阵
今天也想MK代码1 小时前
rust编程实战:实现3d粒子渲染wasm
开发语言·rust·wasm
结衣结衣.1 小时前
【Qt】自定义信号和槽函数
开发语言·c++·qt·c++11
尘鹄2 小时前
一文讲懂Go语言如何使用配置文件连接数据库
开发语言·数据库·后端·golang
qq_433554542 小时前
C++ 二叉搜索树代码
开发语言·c++·算法