how to define duplicated two function with one copy of code in c

Viewed 37

I need two same functions to map to two cores itcm in arm, in a way I can define two function as below

#pragma arm section code="core0itcm"
void function1_core0()
{
  < program body xxx>
}
#pragma arm section code

..
#pragma arm section code="core1itcm"
void function1_core1()
{
    < program body xxx>
}
#pragma arm section code

But in this way, I have to manually maintain the same logic in two different location.

Is there an elegent way to define two function with same "progam body" ? With inline or use advanced use of MACRO?

thanks

1 Answers

If you want to use a macro with multiple lines, you have to use backslash-newline at the end of each line of your program body. See docs.

#define PROGRAM_BODY \
line 1 \
line 2 \
... \
line n-1 \
line n

#pragma arm section code="core0itcm"
void function1_core0()
{
PROGRAM_BODY
}
#pragma arm section code

If you have much code then it may be better to put it in a separate include file. See docs.

#pragma arm section code="core0itcm"
void function1_core0()
{
#include "program_body.h"
}
#pragma arm section code

Both isn't very good programming style but it uses the pre-processor to fill your pragma sections with explicit code.

Update

If you have multiple functions and want only one header file you can vary the core name by defining and redefining a macro:

#pragma arm section code="core0itcm"
#define CORE core0
#include "your_functions.h"
#pragma arm section code

#pragma arm section code="core1itcm"
#undef CORE
#define CORE core1
#include "your_functions.h"
#pragma arm section code

In your_functions.h you can use the macro like this:

#define PASTER(x,y) x ## _ ## y
#define CONCAT(x,y) PASTER(x,y)

void CONCAT(function1, CORE)()
{
  < program body 1>
}

void CONCAT(function2, CORE)()
{
  < program body 2>
}

Credits: https://stackoverflow.com/a/1489985/18667225

Related