让 C 预处理器评估最佳数组维度
Make C preprocessor Evaluate Best Array Dimension
我认为这很容易做到,但我找不到答案。让我们考虑一下这个设置。
// suppose we often change the values of A,B,C
#define A 5
#define B 10
#define C 1
#define SIZE MAX(A+C,B) //find the max somehow
int array[SIZE]
在我的程序中,我有很多参数和复杂的表达式。我正在尝试找出一种方法来找到用于分配数组的最佳值,而无需每次都手动计算它。
要找到 A + B
和 C
之间的最大值,您可以在宏中使用三元表达式。
类似于:
#define A 5
#define B 10
#define C 1
#define MAX(A,B,C) ((((A) + (B)) > (C)) ? ((A) + (B)) : (C))
#define SIZE MAX(A,B,C) //15 the value of A + B
int array[SIZE];
如果要比较的值超过 2 个,您可以将这些值链接起来以找到最大值。
假设您有一个 D
宏,然后您可以执行以下操作:
//...
#define D 20
#define MAX(A,B,C,D) (((((A) + (B)) > C) && (((A) + (B)) > D)) ? ((A) + (B)) : (((C) > (D)) ? (C) : (D)))
#define SIZE MAX(A,B,C,D) //20 the value of D
In my program, I have many parameters and complex expressions.
请记住,可以生成 C 文件(例如,由另一个 C 程序或 Python script, or a GNU guile script, or some GPP script, or some GNU m4 script, or some Lua script, or some GNU gawk script). An example of very useful C code generator is GNU bison(本身主要用 C 编码)。它生成一些解析例程.
因此您可以考虑编写或重用一些 C 代码生成器,然后配置您的 build automation tool (e.g. GNU make) 来编译一些 生成的 C 代码(如果需要,可以适当 #include
编辑)。
另见 GNU autoconf。它会生成一个 configure
脚本,该脚本可以编译多个生成的 C 文件来调整您的软件以适应您的操作系统。
描述生成的 C 代码如何有用的一本有趣的书是 J.Pitrat 的书 Artificial Beings: the Conscience of a Conscious Machine ISBN-13:978-1848211018。
在我的 Bismon software I am generating C code (e.g. files under the modules/
子目录中...)
在 Linux 上,您可以生成 C 代码,将其编译成插件,稍后(在同一进程中)与 dlopen(3) and dlsym(3) 一起使用。
关于生成C代码的思路,另见this。
我认为这很容易做到,但我找不到答案。让我们考虑一下这个设置。
// suppose we often change the values of A,B,C
#define A 5
#define B 10
#define C 1
#define SIZE MAX(A+C,B) //find the max somehow
int array[SIZE]
在我的程序中,我有很多参数和复杂的表达式。我正在尝试找出一种方法来找到用于分配数组的最佳值,而无需每次都手动计算它。
要找到 A + B
和 C
之间的最大值,您可以在宏中使用三元表达式。
类似于:
#define A 5
#define B 10
#define C 1
#define MAX(A,B,C) ((((A) + (B)) > (C)) ? ((A) + (B)) : (C))
#define SIZE MAX(A,B,C) //15 the value of A + B
int array[SIZE];
如果要比较的值超过 2 个,您可以将这些值链接起来以找到最大值。
假设您有一个 D
宏,然后您可以执行以下操作:
//...
#define D 20
#define MAX(A,B,C,D) (((((A) + (B)) > C) && (((A) + (B)) > D)) ? ((A) + (B)) : (((C) > (D)) ? (C) : (D)))
#define SIZE MAX(A,B,C,D) //20 the value of D
In my program, I have many parameters and complex expressions.
请记住,可以生成 C 文件(例如,由另一个 C 程序或 Python script, or a GNU guile script, or some GPP script, or some GNU m4 script, or some Lua script, or some GNU gawk script). An example of very useful C code generator is GNU bison(本身主要用 C 编码)。它生成一些解析例程.
因此您可以考虑编写或重用一些 C 代码生成器,然后配置您的 build automation tool (e.g. GNU make) 来编译一些 生成的 C 代码(如果需要,可以适当 #include
编辑)。
另见 GNU autoconf。它会生成一个 configure
脚本,该脚本可以编译多个生成的 C 文件来调整您的软件以适应您的操作系统。
描述生成的 C 代码如何有用的一本有趣的书是 J.Pitrat 的书 Artificial Beings: the Conscience of a Conscious Machine ISBN-13:978-1848211018。
在我的 Bismon software I am generating C code (e.g. files under the modules/
子目录中...)
在 Linux 上,您可以生成 C 代码,将其编译成插件,稍后(在同一进程中)与 dlopen(3) and dlsym(3) 一起使用。