0
点赞
收藏
分享

微信扫一扫

C/C++混编 extern “C“啥时候用

八卦城的酒 2022-02-15 阅读 40

C/C++混编 extern "C"啥时候用

1.c包含cpp文件

由于cpp有c没有的特性,特别是函数在编译的时候名字定义不一样,导致.c文件链接会出现找不到函数比如报这个错误

Undefined symbol functionname (referred from main.o).

解决方法:

将.cpp对应的.h文件 对应的声明用extern "C"包含起来,例如
cpptest.h

#ifndef CPPTEST_H__
#define CPPTEST_H__

#ifdef __cplusplus
extern "C" {
#endif

#include "stm32h7xx_hal.h"
void cppTestInit(void);
void ledBlink(void);

#ifdef __cplusplus
}
#endif

#endif // !CPPTEST_H__

cpptest.cpp .cpp文件可以正常写

#include "cpptest.h"
void cppTestInit(void){
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  __HAL_RCC_GPIOC_CLK_ENABLE();
  HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET);
  GPIO_InitStruct.Pin = GPIO_PIN_13;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}

void ledBlink(void){
  HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13);
	HAL_Delay(500);
}

main.c

int main(void)
{
  cppTestInit();
  while (1)
  {
    ledBlink();
  }
}





2. cpp包含c文件

这个就比较简单和好理解了,直接在需要使用c的地方使用extern "C"就可以了
例如有三个文件

  • main.cpp
  • testc.c
  • testc.h

testc.c和testc.h就正常写

由于在main.cpp包含test.h

将原本的

#include "test.h"

改成

#ifdef __cplusplus
extern "C" {
#endif

#include "test.h"

#ifdef __cplusplus
}
#endif

就可以了
由于这一部分比较简单,就不放完整例子了

举报

相关推荐

0 条评论