3

I would like something like the following gperf input file:

%{
#include <keywords.h>
// the contents of which contain
// #define KEYWORD1_MACRO "keyword1"
// #define KEYWORD2_MACRO "keyword2"
%}
%%
KEYWORD1_MACRO
KEYWORD2_MACRO
%%

Unfortunately, gperf will interpret those as the stings "KEYWORD1_MACRO", etc.

The reason for this is that I have a protocol spec provided by another party as a header file, containing such #defines. So I don't have control over how they are defined, and I'd rather not have to write another preprocessing tool to #include the header and output the expansion of the macros as quoted strings, only then for use as a gperf input file.

gavinbeatty
  • 319
  • 2
  • 10

1 Answers1

2

I made the following experiment which uses gcc -E to deal with those #includes.

keywords.h:

#define KEYWORD1_MACRO "keyword1"
#define KEYWORD2_MACRO "keyword2"

test.c:

%{
#include "keywords.h"
%}
%%
KEYWORD1_MACRO
KEYWORD2_MACRO
%%

Command: gcc -E -o test.out.txt test.c.
Then, the content in test.out.txt:

# 1 "test.c"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "test.c"
%{
# 1 "keywords.h" 1
# 3 "test.c" 2
%}
%%
"keyword1"
"keyword2"
%%

The #includes are handled automatically. You can then do some text processing and feed into gperf.

timrau
  • 22,578
  • 4
  • 51
  • 64
  • Of course, why ask for gperf to part preprocess when gperf and cpp syntaxes are orthogonal enough. – gavinbeatty Jan 26 '13 at 10:39
  • 1
    I'll be using `cc -xc -E -P keywords.perf.in -o keywords.perf` and /EP with msvc. – gavinbeatty Jan 26 '13 at 10:47
  • [You may also need to 'escape' the pre-processor directives](https://stackoverflow.com/questions/7687634/is-there-a-way-to-escape-a-c-preprocessor-directive) so that they make it through the initial pre-process, through gperf to the generated code to be included. Also gperf's comment convention of a leading '#' does not work well with the pre-processor and you need to escape this as well. It is best to use quoted terminals/keywords with this mode. – artless noise Sep 20 '22 at 13:47