0

我有一个配置文件来定义一些函数和宏。

我的配置文件

#define index_zero  0
#define index_one    1 
#define index_two    2
#define index_three  3
 
unit8 index;

typedef struct
{
   const UINT16   first_value;
   const  UINT16   second_value;
   UINT16   updated_value;
}test;
 
 
test   my_array[3];
 
test   my_array[3] = 
{
    {0, 22, 0},
    {0, 44, 0},
    {0, 33, 0}
};

static void set_zero_value (void)
{
    for(i=0;i<3;i++)
    {
       my_array[i].updated_value = first_value;
    }
}

static void set_temp_value (void)
{
    for(i=0;i<3;i++)
    {
       my_array[i].updated_value = second_value;
    }
}

static UINT16 update_value (uint8 index)
{

     return  (my_array[index].updated_value);

}

我将此 .cfg 文件包含在另一个文件中以更新值,并且我正在定义另一个函数来检查运行状态。

样本1.c

#include "my_config.cfg"
#include "sample1.h"

boolean isrunning(void)
{
  if(condition1)
   return true ;
  else 
    return false ;
}
set_zero_value();
set_temp_value();

在另一个文件中,我正在检查它是否正在运行,如果正在运行,我正在更新我的配置文件中的一些值。

样本2.c

#include "my_config.cfg"
#include "sample1.h"
#include "sample2.h"

if(isrunning())
{
   UINT16 first = update_value(index_zero);
   UINT16 second = update_value(index_one);
   UINT16 third = update_value(index_two);
}

编译代码后,我在链接时收到错误

multiple definition of  `my_array` in object file in sample2.o and sample1.o

multiple definition of  `index` in object file in sample2.o and sample1.o

我不知道为什么在链接时出现此错误,我必须包含两个头文件才能访问这些功能。有什么帮助吗?

4

2 回答 2

0

将您的 cfg 文件包装为条件预处理器指令,例如 #ifndef、#define #endif https://gcc.gnu.org/onlinedocs/gcc-3.0.1/cpp_4.html

于 2018-10-04T18:17:23.827 回答
0

您包含的文件,my_config.cfg包含. 这意味着包含它的每个源文件都包含一个. 然后当这些文件被链接时,你会得到一个错误,因为每个编译的源文件都包含一个副本。my_arraymy_array

您需要将数组的定义移动到单独的源文件中,并将数组的声明放在头文件中。

因此my_config.c,使用以下定义创建:

#include "my_config.cfg"

test my_array[3] = 
{
    {0, 22, 0},
    {0, 44, 0},
    {0, 33, 0}
};

void set_zero_value (void)
{
    for(i=0;i<3;i++)
    {
       my_array[i].updated_value = first_value;
    }
}

void set_temp_value (void)
{
    for(i=0;i<3;i++)
    {
       my_array[i].updated_value = second_value;
    }
}

UINT16 update_value (uint8 index)
{

     return  (my_array[index].updated_value);

}

并将以下声明放入my_config.cfg

#ifndef MY_CONFIG_CFG
#define MY_CONFIG_CFG

#define index_zero  0
#define index_one    1 
#define index_two    2
#define index_three  3

unit8 index;

typedef struct
{
   const UINT16   first_value;
   const  UINT16   second_value;
   UINT16   updated_value;
} test;

extern test  my_array[3];

void set_zero_value (void);
void set_temp_value (void);
UINT16 update_value (uint8 index);

#endif
于 2018-10-04T18:22:31.347 回答