AURIX TriCore C/C++ 混合编程

AURIX TriCore C/C++ 混合编程

AURIX™ Development Studio IDETriCore单片机架构下,写比较大型的工程时强烈需要C++的Class来支持面向对象的思路来组织代码,进行C和C++的混合编程。

软件环境配置

AURIX™ Development Studio IDE中,打开菜单:Project->Properties,然后右侧边栏选择C/C++ Build->Settings,然后在左侧Tool Settings标签页下选择TASKING C/C++ Compiler,修改Command,添加-lcpsx_fpu,例如:

${COMMAND} ${FLAGS} ${OUTPUT_FLAG} ${OUTPUT_PREFIX}${OUTPUT}  ${INPUTS}  -lcpsx_fpu -cs --dep-file="$(@:.src=.d)" --misrac-version=2012 -N0 -Z0 -Y0 2>&1;

然后选择TASKING C/C++ Compiler->Language,修改C++ standards(如ISO C++ 14)

应用,完成修改。

然后我们找到代码文件/Libraries/infineon_libraries/Infra/Platform/Tricore/Compilers/ComplierTasking.c

Ifx_C_Init函数里添加

extern void _Z12__call_ctorsv(void);
_Z12__call_ctorsv();

例如:

void Ifx_C_Init(void)
{
    extern void _c_init(void);

    _c_init();                  /* initialize data */

    // 添加C++初始化
    extern void _Z12__call_ctorsv(void);
    _Z12__call_ctorsv();

}

保存,完成。

代码组织结构

在IDE中,右键添加.cpp.h文件

/*
 * mycpp.h
 *
 */

#ifndef USER_MYCPP_H_
#define USER_MYCPP_H_

#ifdef __cplusplus
 extern "C" {
#endif

int get_test_class_a(void);
void set_test_class_a(int);

#ifdef __cplusplus
 }
#endif


#endif /* USER_MYCPP_H_ */

/*
 * mycpp.cpp
 *
 */

#include "mycpp.h"

class test_class
{
    public:
        int a;
        int b;
} t;

extern "C" int get_test_class_a(){
    return t.a;
}

extern "C" void set_test_class_a(int a){
    t.a = a;
}

上述代码利用了extern "C"__cplusplus宏等技巧,先让C++和C分别编译文件,然后再让C链接到C++已经编译好的函数,这样就可以直接在其他.c里面调用.cpp里面的函数了。

例如:

#include "headfile.h"
#pragma section all "cpu0_dsram"
int core0_main(void)
{
    get_clk();
	IfxCpu_emitEvent(&g_cpuSyncEvent);
	IfxCpu_waitEvent(&g_cpuSyncEvent, 0xFFFF);
    enableInterrupts();
    while (TRUE)
    {
        // 调用cpp函数
        set_test_class_a(get_test_class_a()+1);
        printf("%d\n", get_test_class_a());
        systick_delay_ms(STM0, 1000);
    }
}

#pragma section all restore

另外对于函数我的建议是,写专门的函数让.c调用,不让.c接触到诸如class等C++语言特性的东西。当然也有方法可以让.c文件操作class,但是很麻烦,极简式从C调用C++类方法

参考

AURIX C/C++混合编程_大DDDDD的博客-CSDN博客_c/c++ 混合编程

posted @ 2022-05-09 16:50  Santiego  阅读(614)  评论(0编辑  收藏  举报