'Sharing header file between a C program and a shell script

How can I share a C header file with a shell script?

The shell script communicates with the C program via named pipes. Let us assume that enum SAMPLE_ONE, which is defined in the C header file is written to the pipe by the C program. 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?



Solution 1:[1]

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:

$ 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:

$ 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

Solution 2:[2]

Writing your configuration data in a separate configuration file could be a better approach. For example you could use a "Java properties" format:

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). You could also generate a header file with #defines from this file.

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. 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Raúl Salinas-Monteagudo