简体   繁体   中英

Static array initialization with pointer to extern struct element?

I want to statically initialize an array, but some of its element are pointer to extern struct.

I can't declare the struct as constant, as their element are modified elsewhere, neither static as it clash with extern declaration.

Is there a way to solve this in the static array initialization, or i have to initialize it in a function?

EDIT: looking at your examples after a great launch I just found the error was i was using PWMD2 instead of &PWMD2 (where PWMD2 is the external struct).

Obviously the error was

error: initializer element is not constant

Just to point out what i am doing, the partial of the code (using ChibiOS) is the following:

esc.h

extern struct Engine{
    GPIO_TypeDef *gpio;
    uint8_t pin;

    PWMDriver *driver;
    pwmchannel_t channel;
    pwmcnt_t width;
}engines[];

esc.c

struct Engine engines[] = {
    {GPIOD, 3, &PWMD2, 0, 0},
    {GPIOD, 4, &PWMD2, 1, 0},
    {GPIOD, 6, &PWMD2, 2, 0},
    {GPIOD, 7, &PWMD2, 3, 0},
};

Elaborate on your problem, because the following works ok for me and is what you're asking to do as far as I can tell:

main.c

#include <stdio.h>

#include "externs.h"

static struct_int_t* initextint[1] = { &extint };

int main( int argc, char* argv[] )
{
    printf( "extint: %d\n", initextint[0]->value );
    return 0;
}

externs.h

#ifndef EXTERNS_H
#define EXTERNS_H

typedef struct {
    int value;
    } struct_int_t;

extern struct_int_t extint;

#endif

externs.c

#include "externs.h"

struct_int_t extint = { 10 };

compile:

C:\>gcc main.c externs.c

run:

C:\>a
extint: 10

The following should work for example. What errors are you getting? What compiler and platform are you on? (You could remove const s as appropriate -- they're not essential.)

struct.h :

typedef struct My_struct {
    int n;
} My_struct;

extern const My_struct s1, s2;

struct.c :

#include "struct.h"

const My_struct s1 = { 1 }, s2 = { 2 };

arr.c :

#include <stdio.h>
#include "struct.h"

static const My_struct *const arr[2] = { &s1, &s2 };

int main(void) {
    printf("arr[0]->n = %d, arr[1]->n = %d\n", arr[0]->n, arr[1]->n);

    return 0;
}

Compile with eg

$ gcc arr.c struct.c -o struct_arr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM