首页 > 解决方案 > 在 C++ 中使用配置文件在编译时分配数组

问题描述

我对 c++ 有点陌生,想通过尝试特定项目来了解更多信息。这个项目是一个更大的项目,我想测试一些数值方法“函数”对数组大小等参数的依赖性。我认为组织代码的最佳方式是创建

  1. 实现我要使用的功能的文件
// implement.h
#include <cmath>

struct input_params{
    int input_array_size;
    // other parameters
}

void function(float* , float* , input_params);
// implement.cpp
#include <cmath>
#include "implement.h"

void function(float *input, float *output, input_params args){
    // do stuff
}
  1. 一个配置文件,指定我的 input_params 将包含的内容(带有相应的头文件)
#include "config.h"
input_params args;
#include "implement.h"
#include "config.h"

input_params args;
args.input_array_size = 100; // something I would change before compile time
  1. 将实际运行代码的脚本
#include <cmath>
#include "implement.h"
#include "config.h"

// float *input = new [arg.input_array_size];
float input[arg.input_array_size]; // I want to make this stack-allocated for performance reasons

// float *output = new [arg.output_array_size];
float output[arg.output_array_size]; 

function(input, output, args);

我的问题如下:

  1. 我应该如何使用 g++ 编译代码?
  2. 如何编译我的“配置”文件,以便在编译时知道我的参数?
  3. 有没有更好的替代方法来实际执行此操作?

标签: c++g++software-design

解决方案


最简单的方法是让您的配置文件创建宏:

// config.h
#define ARG_INPUT_SIZE 100
#define ARG_OUTPUT_SIZE 300
// some_other_file.c
#include "config.h"

float input[ARG_INPUT_SIZE];
float output[ARG_OUTPUT_SIZE]; 

在 bss 和堆中分配它实际上不太可能对任何性能指标都有意义。


推荐阅读