This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

C2000: a c macro to a create a variable and place that variable in a specific memory section?

Guru 20035 points

Hello,

Is there a way to define a variable using a macro and then in that same macro place that variable in a specific memory section?  

An example of a variable being placed in a macro is shown below.  I would also like place the pfls in a specific section of memory without having to explicitly write #pragma DATA_SECTION(pfls).

Thanks,

Stephen 

typedef struct
{
    int a;
    int b;
} TEST_STRUCT;

static TEST_STRUCT fls;

#define TEST_MACRO(Type,Variable) \
Type * p ## Variable = &Variable \

TEST_MACRO(TEST_STRUCT,fls);

int main(void) {

	return 0;
}

  • Hello,

    I came up with the answer (see code below).

    Stephen

    typedef struct
    {
        int a;
        int b;
    } TEST_STRUCT;
    
    static TEST_STRUCT fls;
    
    // needed to expands quotes in pragma
    #define EMIT_PRAGMA(x)  _Pragma(#x)
    
    #define TEST_MACRO(Type,Variable,SectionName) \
    EMIT_PRAGMA(DATA_SECTION( p ## Variable ,"SectionName")) \
    Type * p ## Variable = &Variable
    
    TEST_MACRO(TEST_STRUCT,fls,unittestSect);
    
    int main(void) {
    
        int a,b;
    
        fls.a = 123;
        fls.b = 222;
    
        a = pfls->a;
        b = pfls->b;
    
    	return 0;
    }

  • That looks like a reasonable solution.  See this wiki article for a detailed explanation of a similar macro.

    Thanks and regards,

    -George

  • That's interesting. Thanks.
  • The above code works in C, but not C++. Why not?
  • Ok, the following change fixed it.

    #define EMIT_PRAGMA(x)  _Pragma(#x)
    
    #ifdef __cplusplus
    #define TEST_MACRO(Type,Variable,SectionName) \
    EMIT_PRAGMA(DATA_SECTION("SectionName")) \
    Type * p ## Variable = &Variable;
    #else
    #define TEST_MACRO(Type,Variable,SectionName) \
    EMIT_PRAGMA(DATA_SECTION( p ## Variable ,"SectionName")) \
    Type * p ## Variable = &Variable;
    #endif