[英]Sharing header file between a C program and a shell script
How can I share a C header file with a shell script?如何使用 shell 脚本共享 C header 文件?
The shell script communicates with the C program via named pipes. shell 脚本通过命名管道与 C 程序通信。 Let us assume that enum SAMPLE_ONE, which is defined in the C header file is written to the pipe by the C program.
让我们假设 C header 文件中定义的枚举 SAMPLE_ONE 由 C 程序写入 pipe。 The shell script reads out the value of the enum from the pipe. Is there a way to share the header file between the C program and the shell script - in such a way that I only have to update the header file once and not end up having to write the same header constants in the shell script?
shell 脚本从 pipe 中读取枚举的值。有没有办法在 C 程序和 shell 脚本之间共享 header 文件 - 这样我只需要更新 88185530080806 文件一次必须在 shell 脚本中编写相同的 header 常量?
See following example:请参阅以下示例:
$ cat foo.h
#if 0
shopt -s expand_aliases
alias ENUM='true'
alias COMMA=
#else
# define ENUM enum
# define COMMA ,
#endif
ENUM foo_t
{
FOO_VALUE1=11 COMMA
FOO_VALUE2=22 COMMA
FOO_VALUE3=33 COMMA
};
To use in C files:在 C 文件中使用:
$ cat foo.c
#include <stdio.h>
#include "foo.h"
#define print_enum(x) printf("%s=%d\n", #x, x)
int main()
{
enum foo_t foo = FOO_VALUE1;
print_enum(FOO_VALUE1);
print_enum(FOO_VALUE2);
print_enum(FOO_VALUE3);
return 0;
}
To use in Shell scripts:在 Shell 脚本中使用:
$ cat foo.sh
source ./foo.h
enum_names=( ${!FOO_*} )
for name in ${enum_names[@]}; do
echo $name=${!name}
done
Let's test it:让我们测试一下:
$ gcc foo.c
$ ./a.out
FOO_VALUE1=11
FOO_VALUE2=22
FOO_VALUE3=33
$ bash foo.sh
FOO_VALUE1=11
FOO_VALUE2=22
FOO_VALUE3=33
Writing your configuration data in a separate configuration file could be a better approach.将配置数据写入单独的配置文件可能是更好的方法。 For example you could use a "Java properties" format:
例如,您可以使用“Java 属性”格式:
key=value
key2=value2
With C it should not be very difficult to parse, and parsing it with a shell is trivial ( source config.cfg ).使用 C 应该不会很难解析,使用 shell 解析它是微不足道的( source config.cfg )。 You could also generate a header file with #defines from this file.
您还可以从该文件生成带有 #defines 的 header 文件。
My point is that if you need to find a common format as a source for different systems, you should try and use the simplest one.我的观点是,如果您需要找到一种通用格式作为不同系统的来源,您应该尝试使用最简单的格式。 Parsing C preprocessor directives is definitely not so simple.
解析 C 预处理器指令绝对不是那么简单。 Whereas you might be tempted to think that " #define PORT 1234 " maps directly to "port=1234" in the properties format, you could find a "*#define PORT BASE_PORT+1*", which would not be easily properly exported to shell with simple scripts.
虽然您可能会认为“ #define PORT 1234 ”直接映射到属性格式中的“port=1234”,但您会发现“*#define PORT BASE_PORT+1*”,它不容易正确导出到shell 用简单的脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.