How to resolve a yylloc undeclared error? - c

I'm new to flex and bison so bear with me. I'm trying to use yylloc in yyerror to print out where the error occurs along with the filename. I know that this requires me to redefine YYLTPYE to include a char* filename that I can use to keep track of the filename. According to the Flex and Bison book I have, it recommends that I use the YY_USER_ACTION macro to initialize the YYLTYPE in the .l file, so I included the following in it,
#define YY_USER_ACTION yylloc.filename = filename; yylloc.hel = 0; \
yylloc.first_line = yylloc.last_line = yylineno; \
yylloc.first_column = yycolumn; yylloc.last_column = yycolumn+yyleng-1; \
yycolumn += yyleng;
but when I try to compile the project, I get the error that yylloc is undeclared.
I've tried the solution offered by Chris Dodd in this question, but it hasn't helped me to resolve the issue. Any and all help in resolving this error is much apprecaited.
Here's the full code in .l:
%option noyywrap nodefault yylineno case-insensitive
%{
#include "need.h"
#include "numbers.tab.h"
int yycolumn = 1;
#define YY_USER_ACTION yylloc.filename = filename; yylloc.hel = 0; \
yylloc.first_line = yylloc.last_line = yylineno; \
yylloc.first_column = yycolumn; yylloc.last_column = yycolumn+yyleng-1; \
yycolumn += yyleng;
%}
Integers [-]?(0|[1-9][0-9]*)
Float [.][0-9]+
Exp [eE][-]?(0|[1-9][0-9]*)
Octal [-]?(00|0[1-7][0-7]*)
Hexa [-]?(0[xX][0-9A-F]+)
tomsNotNumbers [^ \t\n\v\f\r]+
%%
{Integers}{Float}?{Exp}? {
printf("%s is a number.\n", yytext);
possibleNumbers++; // increment by 1 as an input was given -M
actualNumbers++; // increment by 1 as an input did match our pattern -M
}
{Octal} {
printf("%s is a number.\n", yytext);
possibleNumbers++; // increment by 1 as an input was given -M
actualNumbers++; // increment by 1 as an input did match our pattern -M
}
{Hexa} {
printf("%s is a number.\n", yytext);
possibleNumbers++; // increment by 1 as an input was given -M
actualNumbers++; // increment by 1 as an input did match our pattern -M
}
{tomsNotNumbers} {
printf("%s is not a number.\n", yytext);
yyerror(warning, "This isn't a number.");
possibleNumbers++; // increment by 1 as an input was given -M
failedNumbers++; // increment by 1 as the input has failed to match our patterns -M
}
[\n] /*Do nothing for newline*/
. /*Do nothing for anything else*/
%%
.y is just empty for now, only has an include for need.h and one for .tab.h
The need.h:
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
int possibleNumbers = 0;
int actualNumbers = 0;
int failedNumbers = 0;
typedef struct YYLTYPE
{
int first_line;
int first_column;
int last_line;
int last_column;
char *filename; /* use to keep track of which file we're currently in */
int hel; /* no errors = 0, warning = 1, error = 2, fatal = 3 */
} YYLTYPE;
char *name; /*using for test purposes*/
# define YYLTYPE_IS_DECLARED 1
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (N) \
{ \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
(Current).filename = YYRHSLOC (Rhs, 1).filename; \
(Current).hel = YYRHSLOC (Rhs, 1).hel; \
} \
else \
{ /* empty RHS */ \
(Current).first_line = (Current).last_line = YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = (Current).last_column = YYRHSLOC (Rhs, 0).last_column; \
(Current).filename = NULL; \
(Current).hel = 0; \
} \
while (0)
typedef enum errorSeverity
{
warning = 1, error, fatal
} errorLevel;
void yyerror(errorLevel errlvl, char *s, ...)
{
va_list ap;
va_start(ap, s);
char *errLvls[3] = {"Warning", "Error", "Fatal"};
fprintf(stderr, "%s: %s: , %n", name, errLvls[errlvl - 1], yylloc.first_line);
vfprintf(stderr, s, ap);
fprintf(stderr, "\n");
}
main(int argc, char **argv)
{
printf("argv[0] = %s, argv[1] = %s.\n", argv[0], argv[1]);
if(argc > 1)
{
if((yyin = fopen(argv[1], "r")) == NULL)
{
perror(argv[1]);
exit(1);
}
name = argv[1];
} else
name = "(stdin)";
printf("Filename1: %s", name);
yylex();
printf("Filename2: %s", name);
// print out the report. -M
printf("Out of %d possible numbers, there were %d numbers, and %d not numbers.\n", possibleNumbers, actualNumbers, failedNumbers);
}

Since yylloc is normally defined in the bison-generated parser, not having a bison input file is going to be a bit of a nuisance.
Bison will define yylloc in the generated parser, and place a declaration in the generated header file, if:
You include the directive %locations in the bison prologue, or
You reference a location (#n for some n) in any bison action.
It is generally preferred to add the directive in case there is no explicit reference to a location in any rule.
As Chris Dodd says in the linked question, it is important to include the definition of YYLTYPE before #includeing the bison-generated header file. Alternatively, you could insert the definition of the structure, or an appropriate #include, directly in the bison prologue in a %code requires section. %code requires sections are copied to the generated header, so that will obviate the need to worry about the definition in the flex file.
By the way, I think you meant to use YY_USER_INIT to initialize yylloc. The expansion of YY_USER_INIT is executed only once, before the flex scanner's own initialization. The expansion of YY_USER_ACTION is executed before every scanner action (including empty actions), and is likely to be of use to update the yylloc structure with the current token.

Related

Remove code between #if 0 and #endif when exporting a C file to a new one

I want to remove all comments in a toy.c file. From Remove comments from C/C++ code I see that I could use
gcc -E -fpreprocessed -P -dD toy.c
But some of my code (say deprecated functions that I don't want to compile) are wrapped up between #if 0 and endif, as if they were commented out.
One one hand, the above command does not remove this type of "comment" because its removal is only possible during macro expansion, which -fpreprocessed prevents;
On the other hand, I have other macros I don't want to expand, so dropping -fpreprocessed is a bad idea.
I see a dilemma here. Is there a way out of this situation? Thanks.
The following toy example "toy.c" is sufficient to illustrate the problem.
#define foo 3 /* this is a macro */
// a toy function
int main (void) {
return foo;
}
// this is deprecated
#if 0
int main (void) {
printf("%d\n", foo);
return 0;
}
#endif
gcc -E -fpreprocessed -P -dD toy.c gives
#define foo 3
int main (void) {
return foo;
}
#if 0
int main (void) {
printf("%d\n", foo);
return 0;
}
#endif
while gcc -E -P toy.c gives
int main (void) {
return 3;
}
There's a pair of programs, sunifdef ("Son of unifdef", which is available from unifdef) and coan, that can be used to do what you want. The question Is there a C pre-processor which eliminates #ifdef blocks based on values defined/undefined? has answers which discuss these programs.
For example, given "xyz37.c":
#define foo 3 /* this is a macro */
// a toy function
int main (void) {
return foo;
}
// this is deprecated
#if 0
int main (void) {
printf("%d\n", foo);
}
#endif
Using sunifdef
sunifdef -DDEFINED -ned < xyz37.c
gives
#define foo 3 /* this is a macro */
// a toy function
int main (void) {
return foo;
}
// this is deprecated
and given this file "xyz23.c":
#if 0
This is deleted
#else
This is not deleted
#endif
#if 0
Deleted
#endif
#if defined(XYZ)
XYZ is defined
#else
XYZ is not defined
#endif
#if 1
This is persistent
#else
This is inconsistent
#endif
The program
sunifdef -DDEFINE -ned < xyz23.c
gives
This is not deleted
#if defined(XYZ)
XYZ is defined
#else
XYZ is not defined
#endif
This is persistent
This is, I think, what you're after. The -DDEFINED options seems to be necessary; choose any name that you do not use in your code. You could use -UNEVER_DEFINE_THIS instead, if you prefer. The -ned option evaluates the constant terms and eliminates the relevant code. Without it, the constant terms like 0 and 1 are not eliminated.
I've used sunifdef happily for a number of years (encroaching on a decade). I've not yet found it to make a mistake, and I've used it to clean up some revoltingly abstruse sets of 'ifdeffery'. The program coan is a development of sunifdef with even more capabilities.
The preprocessor doesn't make exceptions. You cannot use it here to do that.
A simple state machine using python can work. It even handles nesting (well, maybe not all cases are covered like nested #if 0 but you can compare the source before & after and manually validate). Also commented code isn't supported (but it seems that you have it covered)
the input (slightly more complex than yours for the demo):
#define foo 3
int main (void) {
return foo;
}
#if 0
int main (void) {
#ifdef DDD
printf("%d\n", foo);
#endif
}
#endif
void other_function()
{}
now the code, using regexes to detect #if & #endif.
import re
rif0 = re.compile("\s*#if\s+0")
rif = re.compile("\s*#(if|ifn?def)")
endif = re.compile("\s*#endif")
if_nesting = 0
if0_nesting = 0
suppress = False
with open("input.c") as fin, open("output.c","w") as fout:
for l in fin:
if rif.match(l):
if_nesting += 1
if rif0.match(l):
suppress = True
if0_nesting = if_nesting
elif endif.match(l):
if if0_nesting == if_nesting:
suppress = False
if_nesting -= 1
continue # don't write the #endif
if not suppress:
fout.write(l))
the output file contains:
#define foo 3
int main (void) {
return foo;
}
void other_function()
{}
so the nesting worked and the #if 0 part was successfully removed. Not something that sed "/#if 0/,/#endif/d can achieve.
Thanks for the other two answers.
I am now aware of unifdef and sunifdef. I am happy to know the existence of these tools, and that I am not the only one who wants to do this kind of code cleaning.
I have also written a rm_if0_endif.c (attached below) for removing an #if 0 ... #endif block which is sufficient for me. Its philosophy is based on text processing. It scans an input C script, locating #if 0 and the correct enclosing endif, so that this block can be omitted during char-to-char copying.
The text processing approach is limited, as it is designed for #if 0 ... #endif case only, but is all I need for now. A C program is not the only way for this kind of text processing. Jean-François Fabre's answer demonstrates how to do it in Python. I can also do something similar in R, using readLines, startsWith and writeLines. I chose to do it in C as I am not yet an expert in C so this task drives me to learn. Here is a demo of my rm_if0_endif.c. Note that the program can concatenate several C files and add header for each file.
original input file input.c
#define foo 3 /* this is a macro */
// a toy function
int test1 (void) {
return foo;
}
#if 0
#undef foo
#define foo 4
#ifdef bar
#warning "??"
#endif
// this is deprecated
int main (void) {
printf("%d\n", foo);
return 0;
}
#endif
// another toy
int test2 (void) {
return foo;
}
gcc pre-processing output "gcc_output.c" (taken as input for my program)
gcc -E -fpreprocessed -P -dD input.c > gcc_output.c
#define foo 3
int test1 (void) {
return foo;
}
#if 0
#undef foo
#define foo 4
#ifdef bar
#warning "??"
#endif
int main (void) {
printf("%d\n", foo);
return 0;
}
#endif
int test2 (void) {
return foo;
}
final output final_output.c from my program
rm_if0_endif.c has a utility function pattern_matching and a workhorse function rm_if0_endif:
void rm_if0_endif (char *InputFile,
char *OutputFile, char *WriteMode, char *OutputHeader);
The attached file below has a main function, doing
rm_if0_endif("gcc_output.c",
"final_output.c", "w", "// this is a demo of 'rm_if0_endif.c'\n");
It produces:
// this is a demo of 'rm_if0_endif.c'
#define foo 3
int test1 (void) {
return foo;
}
int test2 (void) {
return foo;
}
Appendix: rm_if0_endif.c
#include <stdio.h>
int pattern_matching (FILE *fp, const char *pattern, int length_pattern) {
int flag = 1;
int i, c;
for (i = 0; i < length_pattern; i++) {
c = fgetc(fp);
if (c != pattern[i]) {
flag = 0; break;
}
}
return flag;
}
void rm_if0_endif (char *InputFile,
char *OutputFile, char *WriteMode, char *OutputHeader) {
FILE *fp_r = fopen(InputFile, "r");
FILE *fp_w = fopen(OutputFile, WriteMode);
fpos_t pos;
if (fp_r == NULL) perror("error when opening input file!");
fputs(OutputHeader, fp_w);
int c, i, a1, a2;
int if_0_flag, if_flag, endif_flag, EOF_flag;
const char *if_0 = "if 0";
const char *endif = "endif";
EOF_flag = 0;
while (EOF_flag == 0) {
do {
c = fgetc(fp_r);
while ((c != '#') && (c != EOF)) {
fputc(c, fp_w);
c = fgetc(fp_r);
}
if (c == EOF) {
EOF_flag = 1; break;
}
fgetpos(fp_r, &pos);
if_0_flag = pattern_matching(fp_r, if_0, 4);
fsetpos(fp_r, &pos);
if (if_0_flag == 0) fputc('#', fp_w);
} while (if_0_flag == 0);
if (EOF_flag == 1) break;
a1 = 1; a2 = 0;
do {
c = fgetc(fp_r);
while (c != '#') c = fgetc(fp_r);
fgetpos(fp_r, &pos);
if_flag = pattern_matching(fp_r, if_0, 2);
fsetpos(fp_r, &pos);
if (if_flag == 1) a1++;
fgetpos(fp_r, &pos);
endif_flag = pattern_matching(fp_r, endif, 5);
fsetpos(fp_r, &pos);
if (endif_flag == 1) a2++;
} while (a1 != a2);
for (i = 0; i < 5; i++) c = fgetc(fp_r);
if (c == EOF) {
EOF_flag == 1;
}
}
fclose(fp_r);
fclose(fp_w);
}
int main (void) {
rm_if0_endif("gcc_output.c",
"final_output.c", "w", "// this is a demo of 'rm_if0_endif.c'\n");
return 0;
}

How to define an array of structs at compile time composed of static (private) structs from separate modules?

This question is something of a trick C question or a trick clang/gcc question. I'm not sure which.
I phrased it like I did because the final array is in main.c, but the structs that are in the array are defined in C modules.
The end goal of what I am trying to do is to be able to define structs in seperate C modules and then have those structs be available in a contiguous array right from program start. I do not want to use any dynamic code to declare the array and put in the elements.
I would like it all done at compile or link time -- not at run time.
I'm looking to end up with a monolithic blob of memory that gets setup right from program start.
For the sake of the Stack Overflow question, I thought it would make sense if I imagined these as "drivers" (like in the Linux kernel) Going with that...
Each module is a driver. Because the team is complex, I do not know how many drivers there will ultimately be.
Requirements:
Loaded into contiguous memory (an array)
Loaded into memory at program start
installed by the compiler/linker, not dynamic code
a driver exists because source code exists for it (no dynamic code to load them up)
Avoid cluttering up the code
Here is a contrived example:
// myapp.h
//////////////////////////
struct state
{
int16_t data[10];
};
struct driver
{
char name[255];
int16_t (*on_do_stuff) (struct state *state);
/* other stuff snipped out */
};
// drivera.c
//////////////////////////
#include "myapp.h"
static int16_t _on_do_stuff(struct state *state)
{
/* do stuff */
}
static const struct driver _driver = {
.name = "drivera",
.on_do_stuff = _on_do_stuff
};
// driverb.c
//////////////////////////
#include "myapp.h"
static int16_t _on_do_stuff(struct state *state)
{
/* do stuff */
}
static const struct driver _driver = {
.name = "driverb",
.on_do_stuff = _on_do_stuff
};
// driverc.c
//////////////////////////
#include "myapp.h"
static int16_t _on_do_stuff(struct state *state)
{
/* do stuff */
}
static const struct driver _driver = {
.name = "driverc",
.on_do_stuff = _on_do_stuff
};
// main.c
//////////////////////////
#include <stdio.h>
static struct driver the_drivers[] = {
{drivera somehow},
{driverb somehow},
{driverc somehow},
{0}
};
int main(void)
{
struct state state;
struct driver *current = the_drivers;
while (current != 0)
{
printf("we are up to %s\n", current->name);
current->on_do_stuff(&state);
current += sizeof(struct driver);
}
return 0;
}
This doesn't work exactly.
Ideas:
On the module-level structs, I could remove the static const keywords, but I'm not sure how to get them into the array at compile time
I could move all of the module-level structs to main.c, but then I would need to remove the static keyword from all of the on_do_stuff functions, and thereby clutter up the namespace.
In the Linux kernel, they somehow define kernel modules in separate files and then through linker magic, they are able to be loaded into monolithics
Use a dedicated ELF section to "collect" the data structures.
For example, define your data structure in info.h as
#ifndef INFO_H
#define INFO_H
#ifndef INFO_ALIGNMENT
#if defined(__LP64__)
#define INFO_ALIGNMENT 16
#else
#define INFO_ALIGNMENT 8
#endif
#endif
struct info {
long key;
long val;
} __attribute__((__aligned__(INFO_ALIGNMENT)));
#define INFO_NAME(counter) INFO_CAT(info_, counter)
#define INFO_CAT(a, b) INFO_DUMMY() a ## b
#define INFO_DUMMY()
#define DEFINE_INFO(data...) \
static struct info INFO_NAME(__COUNTER__) \
__attribute__((__used__, __section__("info"))) \
= { data }
#endif /* INFO_H */
The INFO_ALIGNMENT macro is the alignment used by the linker to place each symbol, separately, to the info section. It is important that the C compiler agrees, as otherwise the section contents cannot be treated as an array. (You'll obtain an incorrect number of structures, and only the first one (plus every N'th) will be correct, the rest of the structures garbled. Essentially, the C compiler and the linker disagreed on the size of each structure in the section "array".)
Note that you can add preprocessor macros to fine-tune the INFO_ALIGNMENT for each of the architectures you use, but you can also override it for example in your Makefile, at compile time. (For GCC, supply -DINFO_ALIGNMENT=32 for example.)
The used attribute ensures that the definition is emitted in the object file, even though it is not referenced otherwise in the same data file. The section("info") attribute puts the data into a special info section in the object file. The section name (info) is up to you.
Those are the critical parts, otherwise it is completely up to you how you define the macro, or whether you define it at all. Using the macro is easy, because one does not need to worry about using unique variable name for the structure. Also, if at least one member is specified, all others will be initialized to zero.
In the source files, you define the data objects as e.g.
#include "info.h"
/* Suggested, easy way */
DEFINE_INFO(.key = 5, .val = 42);
/* Alternative way, without relying on any macros */
static struct info foo __attribute__((__used__, __section__("info"))) = {
.key = 2,
.val = 1
};
The linker provides symbols __start_info and __stop_info, to obtain the structures in the info section. In your main.c, use for example
#include "info.h"
extern struct info __start_info[];
extern struct info __stop_info[];
#define NUM_INFO ((size_t)(__stop_info - __start_info))
#define INFO(i) ((__start_info) + (i))
so you can enumerate all info structures. For example,
int main(void)
{
size_t i;
printf("There are %zu info structures:\n", NUM_INFO);
for (i = 0; i < NUM_INFO; i++)
printf(" %zu. key=%ld, val=%ld\n", i,
__start_info[i].key, INFO(i)->val);
return EXIT_SUCCESS;
}
For illustration, I used both the __start_info[] array access (you can obviously #define SOMENAME __start_info if you want, just make sure you do not use SOMENAME elsewhere in main.c, so you can use SOMENAME[] as the array instead), as well as the INFO() macro.
Let's look at a practical example, an RPN calculator.
We use section ops to define the operations, using facilities defined in ops.h:
#ifndef OPS_H
#define OPS_H
#include <stdlib.h>
#include <errno.h>
#ifndef ALIGN_SECTION
#if defined(__LP64__) || defined(_LP64)
#define ALIGN_SECTION __attribute__((__aligned__(16)))
#elif defined(__ILP32__) || defined(_ILP32)
#define ALIGN_SECTION __attribute__((__aligned__(8)))
#else
#define ALIGN_SECTION
#endif
#endif
typedef struct {
size_t maxsize; /* Number of values allocated for */
size_t size; /* Number of values in stack */
double *value; /* Values, oldest first */
} stack;
#define STACK_INITIALIZER { 0, 0, NULL }
struct op {
const char *name; /* Operation name */
const char *desc; /* Description */
int (*func)(stack *); /* Implementation */
} ALIGN_SECTION;
#define OPS_NAME(counter) OPS_CAT(op_, counter, _struct)
#define OPS_CAT(a, b, c) OPS_DUMMY() a ## b ## c
#define OPS_DUMMY()
#define DEFINE_OP(name, func, desc) \
static struct op OPS_NAME(__COUNTER__) \
__attribute__((__used__, __section__("ops"))) = { name, desc, func }
static inline int stack_has(stack *st, const size_t num)
{
if (!st)
return EINVAL;
if (st->size < num)
return ENOENT;
return 0;
}
static inline int stack_pop(stack *st, double *to)
{
if (!st)
return EINVAL;
if (st->size < 1)
return ENOENT;
st->size--;
if (to)
*to = st->value[st->size];
return 0;
}
static inline int stack_push(stack *st, double val)
{
if (!st)
return EINVAL;
if (st->size >= st->maxsize) {
const size_t maxsize = (st->size | 127) + 129;
double *value;
value = realloc(st->value, maxsize * sizeof (double));
if (!value)
return ENOMEM;
st->maxsize = maxsize;
st->value = value;
}
st->value[st->size++] = val;
return 0;
}
#endif /* OPS_H */
The basic set of operations is defined in ops-basic.c:
#include "ops.h"
static int do_neg(stack *st)
{
double temp;
int retval;
retval = stack_pop(st, &temp);
if (retval)
return retval;
return stack_push(st, -temp);
}
static int do_add(stack *st)
{
int retval;
retval = stack_has(st, 2);
if (retval)
return retval;
st->value[st->size - 2] = st->value[st->size - 1] + st->value[st->size - 2];
st->size--;
return 0;
}
static int do_sub(stack *st)
{
int retval;
retval = stack_has(st, 2);
if (retval)
return retval;
st->value[st->size - 2] = st->value[st->size - 1] - st->value[st->size - 2];
st->size--;
return 0;
}
static int do_mul(stack *st)
{
int retval;
retval = stack_has(st, 2);
if (retval)
return retval;
st->value[st->size - 2] = st->value[st->size - 1] * st->value[st->size - 2];
st->size--;
return 0;
}
static int do_div(stack *st)
{
int retval;
retval = stack_has(st, 2);
if (retval)
return retval;
st->value[st->size - 2] = st->value[st->size - 1] / st->value[st->size - 2];
st->size--;
return 0;
}
DEFINE_OP("neg", do_neg, "Negate current operand");
DEFINE_OP("add", do_add, "Add current and previous operands");
DEFINE_OP("sub", do_sub, "Subtract previous operand from current one");
DEFINE_OP("mul", do_mul, "Multiply previous and current operands");
DEFINE_OP("div", do_div, "Divide current operand by the previous operand");
The calculator expects each value and operand to be a separate command-line argument for simplicity. Our main.c contains operation lookup, basic usage, value parsing, and printing the result (or error):
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "ops.h"
extern struct op __start_ops[];
extern struct op __stop_ops[];
#define NUM_OPS ((size_t)(__stop_ops - __start_ops))
static int do_op(stack *st, const char *opname)
{
struct op *curr_op;
if (!st || !opname)
return EINVAL;
for (curr_op = __start_ops; curr_op < __stop_ops; curr_op++)
if (!strcmp(opname, curr_op->name))
break;
if (curr_op >= __stop_ops)
return ENOTSUP;
return curr_op->func(st);
}
static int usage(const char *argv0)
{
struct op *curr_op;
fprintf(stderr, "\n");
fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv0);
fprintf(stderr, " %s RPN-EXPRESSION\n", argv0);
fprintf(stderr, "\n");
fprintf(stderr, "Where RPN-EXPRESSION is an expression using reverse\n");
fprintf(stderr, "Polish notation, and each argument is a separate value\n");
fprintf(stderr, "or operator. The following operators are supported:\n");
for (curr_op = __start_ops; curr_op < __stop_ops; curr_op++)
fprintf(stderr, "\t%-14s %s\n", curr_op->name, curr_op->desc);
fprintf(stderr, "\n");
return EXIT_SUCCESS;
}
int main(int argc, char *argv[])
{
stack all = STACK_INITIALIZER;
double val;
size_t i;
int arg, err;
char dummy;
if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))
return usage(argv[0]);
for (arg = 1; arg < argc; arg++)
if (sscanf(argv[arg], " %lf %c", &val, &dummy) == 1) {
err = stack_push(&all, val);
if (err) {
fprintf(stderr, "Cannot push %s to stack: %s.\n", argv[arg], strerror(err));
return EXIT_FAILURE;
}
} else {
err = do_op(&all, argv[arg]);
if (err == ENOTSUP) {
fprintf(stderr, "%s: Operation not supported.\n", argv[arg]);
return EXIT_FAILURE;
} else
if (err) {
fprintf(stderr, "%s: Cannot perform operation: %s.\n", argv[arg], strerror(err));
return EXIT_FAILURE;
}
}
if (all.size < 1) {
fprintf(stderr, "No result.\n");
return EXIT_FAILURE;
} else
if (all.size > 1) {
fprintf(stderr, "Multiple results:\n");
for (i = 0; i < all.size; i++)
fprintf(stderr, " %.9f\n", all.value[i]);
return EXIT_FAILURE;
}
printf("%.9f\n", all.value[0]);
return EXIT_SUCCESS;
}
Note that if there were many operations, constructing a hash table to speed up the operation lookup would make a lot of sense.
Finally, we need a Makefile to tie it all together:
CC := gcc
CFLAGS := -Wall -O2 -std=c99
LDFLAGS := -lm
OPS := $(wildcard ops-*.c)
OPSOBJS := $(OPS:%.c=%.o)
PROGS := rpncalc
.PHONY: all clean
all: clean $(PROGS)
clean:
rm -f *.o $(PROGS)
%.o: %.c
$(CC) $(CFLAGS) -c $^
rpncalc: main.o $(OPSOBJS)
$(CC) $(CFLAGS) $^ $(LDFLAGS) -o $#
Because this forum does not preserve Tabs, and make requires them for indentation, you probably need to fix the indentation after copy-pasting the above. I use sed -e 's|^ *|\t|' -i Makefile
If you compile (make clean all) and run (./rpncalc) the above, you'll see the usage information:
Usage: ./rpncalc [ -h | --help ]
./rpncalc RPN-EXPRESSION
Where RPN-EXPRESSION is an expression using reverse
Polish notation, and each argument is a separate value
or operator. The following operators are supported:
div Divide current operand by the previous operand
mul Multiply previous and current operands
sub Subtract previous operand from current one
add Add current and previous operands
neg Negate current operand
and if you run e.g. ./rpncalc 3.0 4.0 5.0 sub mul neg, you get the result 3.000000000.
Now, let's add some new operations, ops-sqrt.c:
#include <math.h>
#include "ops.h"
static int do_sqrt(stack *st)
{
double temp;
int retval;
retval = stack_pop(st, &temp);
if (retval)
return retval;
return stack_push(st, sqrt(temp));
}
DEFINE_OP("sqrt", do_sqrt, "Take the square root of the current operand");
Because the Makefile above compiles all C source files beginning with ops- in to the final binary, the only thing you need to do is recompile the source: make clean all. Running ./rpncalc now outputs
Usage: ./rpncalc [ -h | --help ]
./rpncalc RPN-EXPRESSION
Where RPN-EXPRESSION is an expression using reverse
Polish notation, and each argument is a separate value
or operator. The following operators are supported:
sqrt Take the square root of the current operand
div Divide current operand by the previous operand
mul Multiply previous and current operands
sub Subtract previous operand from current one
add Add current and previous operands
neg Negate current operand
and you have the new sqrt operator available.
Testing e.g. ./rpncalc 1 1 1 1 add add add sqrt yields 2.000000000, as expected.

Using parsers in GNU automake in c

I am new to GNU autotools and in my project lex and yacc parsers are used.Including them as source in makefile.am produes following error :
configure.in :
...
AC_CHECK_PROGS(YACC,bison yacc,none)
if test "x$YACC" = "xbison"; then
YACC="$YACC -y"
fi
AC_CHECK_PROGS(LEX,flex,none)
...
makefile.am :
## $Id
AUTOMAKE_OPTIONS=foreign no-dependencies
include $(srcdir)/Makefile_defs
dynamicpreprocessordir = ${libdir}/snort_dynamicpreprocessor
dynamicpreprocessor_LTLIBRARIES = libsf_appid_preproc.la
libsf_appid_preproc_la_LDFLAGS = -export-dynamic -module #XCCFLAGS#
if SO_WITH_STATIC_LIB
libsf_appid_preproc_la_LIBADD = ../libsf_dynamic_preproc.la
../libsf_dynamic_utils.la $(LUA_LIBS)
else
nodist_libsf_appid_preproc_la_SOURCES = \
../include/sf_dynamic_preproc_lib.c \
../include/sf_ip.c \
../include/sfPolicyUserData.c \
../include/sfxhash.c \
../include/sfghash.c \
../include/sflsq.c \
../include/sfhashfcn.c \
../include/sfmemcap.c \
../include/sfprimetable.c
libsf_appid_preproc_la_LIBADD = $(LUA_LIBS)
endif
libsf_appid_preproc_la_CFLAGS = -DDYNAMIC_PREPROC_CONTEXT -DSTATIC=static $(LUA_CFLAGS)
libsf_appid_preproc_la_SOURCES = $(APPID_SOURCES)
all-local: $(LTLIBRARIES)
$(MAKE) DESTDIR=`pwd`/../build install-dynamicpreprocessorLTLIBRARIES
In Makefile_defs :
APPID_SRC_DIR = ${top_srcdir}/src/dynamic-preprocessors/appid
...
APPID_SOURCES = \
$(APPID_SRC_DIR)/vfml/fc45.lex \
$(APPID_SRC_DIR)/vfml/fc45.y \
...
when i run the program i get following error :
libsf_appid_preproc.so: undefined symbol: FC45SetFile
While FC45SetFile() is already defined in fc45.lex file.
fc45.lex :
%{
#include "fc45.tab.h"
//#include "vfml.h"
#include <string.h>
#include <stdlib.h>
/* HERE doesn't match strings starting with numbers other than 0 right */
char string_buf[4000]; /* BUG - maybe check for strings that are too long? */
char *string_buf_ptr;
void FC45FinishString(void);
extern int gLineNumber;
%}
%x str_rule
%%
<str_rule,INITIAL>\|[^\n]* ;
[\ \t\r]+ ;
\n gLineNumber++;
\. { return '.';}
, { return ',';}
: { return ':';}
ignore { return tIgnore; }
continuous { return tContinuous; }
discrete { return tDiscrete; }
[^:?,\t\n\r\|\.\\\ ] string_buf_ptr = string_buf; unput(yytext[0]); BEGIN(str_rule);
<str_rule>[:,?] FC45FinishString(); unput(yytext[0]); return tString;
<str_rule>\.[\t\r\ ] FC45FinishString(); unput(yytext[1]); unput(yytext[0]); return tString;
<str_rule>\.\n FC45FinishString(); unput(yytext[1]); unput(yytext[0]); return tString; gLineNumber++;
<str_rule><<EOF>> {
int len = strlen(string_buf);
// printf("eof rule.\n");
if(len == 1 && string_buf[0] == '.') {
//printf(" period at end of file\n");
return '.';
} else if(string_buf[len - 1] == '.') {
// printf(" period: %s - unput .\n", string_buf);
FC45FinishString(); unput('.'); return tString;
} else {
// printf(" no-period: %s\n", string_buf);
FC45FinishString(); return tString;
}
}
<str_rule>\\: *string_buf_ptr++ = ':';
<str_rule>\\\? *string_buf_ptr++ = '?';
<str_rule>\\, *string_buf_ptr++ = ',';
<str_rule>\\. *string_buf_ptr++ = '.';
<str_rule>\n *string_buf_ptr++ = ' '; gLineNumber++;
<str_rule>[ \t\r]+ *string_buf_ptr++ = ' ';
<str_rule>[^:?,\t\n\r\|\.\\\ ]+ {
char *yptr = yytext;
while(*yptr) {
*string_buf_ptr++ = *yptr++;
}
}
%%
int fc45wrap(void) {
return 1;
}
void FC45SetFile(FILE *file) {
fc45in = file;
yyrestart(fc45in);
}
void FC45FinishString(void) {
int len;
char *tmpStr;
BEGIN(INITIAL);
*string_buf_ptr = '\0';
len = strlen(string_buf);
/* remove any ending spaces */
while(string_buf[len - 1] == ' ') {
string_buf[len - 1] = '\0';
len--;
}
tmpStr = MNewPtr(len + 1);
strncpy(tmpStr, string_buf, len + 1);
fc45lval.string = tmpStr;
string_buf[0] = '\0';
}
fc45.y :
%{
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "ExampleSpec1.h"
//#include "AttributeTracker.c"
//#include "vfml.h"
%}
%{
int fc45lex(void);
int fc45error(const char *);
/* HERE figure out how to give better error messages */
/* BUG needs a \n at the end of the names file */
/* These tmps are allocated at the begining of parsing and then
used during parsing. For example, so that we can simply
add terrains to an area while parsing. After parsing a
statement, the associated tmp is added to the appropriate
global list, and a new tmp is allocated. Finally, at the
end of parsing, all the tmps are freed
*/
ExampleSpecPtr exampleSpec;
AttributeSpecPtr attributeSpec;
int gLineNumber;
%}
%union {
int integer;
float f;
char *string;
}
%token <integer> tInteger
%token <string> tString
%token tIgnore tContinuous tDiscrete tEOF
%%
ExampleSpec: ClassList '.' AttributeList;
ClassList: ClassList ',' ClassSpec | ClassSpec /* ending */;
ClassSpec: tString { ExampleSpecAddClass(exampleSpec, $1); };
AttributeList: AttributeList AttributeSpec | /* ending */;
AttributeSpec: tString ':' AttributeInfo '.' {
AttributeSpecSetName(attributeSpec, $1);
ExampleSpecAddAttributeSpec(exampleSpec, attributeSpec);
attributeSpec = AttributeSpecNew();
};
AttributeInfo: tIgnore {
AttributeSpecSetType(attributeSpec, asIgnore);} |
tContinuous {
AttributeSpecSetType(attributeSpec, asContinuous);} |
tDiscrete tString {
AttributeSpecSetType(attributeSpec, asDiscreteNoName);
AttributeSpecSetNumValues(attributeSpec, atoi($2)); } |
AttributeValueNameList {
AttributeSpecSetType(attributeSpec, asDiscreteNamed); };
AttributeValueNameList: AttributeValueNameList ',' tString {
AttributeSpecSetNumValues(attributeSpec,
AttributeSpecGetNumValues(attributeSpec) + 1);
AttributeSpecAddValue(attributeSpec, $3); } |
tString {
AttributeSpecSetNumValues(attributeSpec,
AttributeSpecGetNumValues(attributeSpec) + 1);
AttributeSpecAddValue(attributeSpec, $1); };
%%
void FC45SetFile(FILE *file);
int fc45error(const char *msg) {
fprintf(stderr, "%s line %d\n", msg, gLineNumber);
return 0;
}
ExampleSpecPtr ParseFC45(const char *file) {
FILE *input;
input = fopen(file, "r");
if(input == 0) {
return 0;
}
FC45SetFile(input);
exampleSpec = ExampleSpecNew();
attributeSpec = AttributeSpecNew();
gLineNumber = 0;
if(fc45parse()) {
/* parse failed! */
fprintf(stderr, "Error in parsing: %s\n", file);
}
fclose(input);
/* free the left over attribute spec */
AttributeSpecFree(attributeSpec);
return exampleSpec;
}
I've searched Internet for the solution and was unable to come up with any.
Hope someone recognizes the problem and has a quick solution to it. Any help will be appreciated.
I just ran through a simple example, adding the following Autotools files:
configure.ac:
AC_PREREQ([2.69])
AC_INIT([example], [0.1a], [example#example.com])
AC_CONFIG_SRCDIR([ex1.l])
# Used only to shorten the otherwise lengthy compilation line in the output below.
AC_CONFIG_HEADERS([config.h])
AM_INIT_AUTOMAKE([foreign])
# I used C instead of C++.
AC_PROG_CC
AM_PROG_LEX
AC_PROG_YACC
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
Makefile.am (taken pretty much straight from the Automake manual):
BUILT_SOURCES = ex1.h
AM_YFLAGS = -d
bin_PROGRAMS = ex1
ex1_SOURCES = ex1.l ex1.y
It turned out that you can't name the files with the same base file name. In my case, I had ex1.l and ex1.y. Using ex1_SOURCES = ex1.l ex1.y resulted in the following output when I invoked make:
make[1]: Entering directory '/home/kit/ex1'
/bin/bash ./ylwrap ex1.l lex.yy.c ex1.c -- flex
make[1]: Leaving directory '/home/kit/ex1'
make all-am
make[1]: Entering directory '/home/kit/ex1'
gcc -DHAVE_CONFIG_H=1 -I. -g -O2 -MT ex1.o -MD -MP -MF .deps/ex1.Tpo -c -o ex1.o ex1.c
ex1.l:5:17: fatal error: ex1.h: No such file or directory
#include "ex1.h"
^
compilation terminated.
Makefile:378: recipe for target 'ex1.o' failed
make[1]: *** [ex1.o] Error 1
make[1]: Leaving directory '/home/kit/ex1'
Makefile:281: recipe for target 'all' failed
make: *** [all] Error 2
Note the fact that flex was invoked in the second line, but bison/yacc was not. What's the reason? Well, the ylwrap script is the reason:
ex1.c: ex1.l
ex1.c: ex1.y
Because the script renames the output of ex1.l from "lex.yy.c" to "ex1.c", the makefile thinks that ex1.c is already built, so it won't do anything with the bison/yacc file, which means that ex1.h isn't built either.
You can't disable the ylwrap script, but you can work around it: simply rename your flex source file and change the references to the file name in your Makefile.in and configure.ac files as necessary. You shouldn't need to rename your bison/yacc source file because that would mean changing every #include "fc45.h" to #include "fc45_g.h" (or whatever you renamed the file to) in every C file as well as your flex source file.
The problem is that neither make nor automake know anything about the non-standard .lex file extension, so when you have a source file that ends in .lex, they don't know what to do with it. You could create rules to handle .lex, but it's probably much easier to just rename the file with a .l file extension, which they know how to handle.

How to determine if a pointer equals an element of an array?

I have code in Code Reveiw that "works" as expected, yet may have UB
.
Code has an array of same-sized char arrays called GP2_format[]. To detect if the pointer format has the same value as the address of one of the elements GP2_format[][0], the below code simple tested if the pointer was >= the smallest element and <= the greatest. As the elements are size 1, no further checking needed.
const char GP2_format[GP2_format_N + 1][1];
const char *format = ...;
if (format >= GP2_format[0] && format <= GP2_format[GP2_format_N]) Inside()
else Outside();
C11 §6.5.8/5 Relational operators < > <= >= appears to define this as the dreaded Undefined Behavior when comparing a pointer from outside the array.
When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the
same object, ... of the same array object, they compare equal. ...(same object OK) .... (same union OK) .... (same array OK) ... In all other cases, the behavior is undefined.
Q1 Is code's pointer compare in GP2_get_type() UB?
Q2 If so, what is a well defined alternate, search O(1), to the questionable GP2_get_type()?
Slower solutions
Code could sequentially test format against each GP2_format[] or convert the values to intptr_t, sort one time and do a O(ln2(n)) search.
Similar
...if a pointer is part of a set, but this "set" is not random, it is an array.
intptr_t approach - maybe UB.
#include <stdio.h>
typedef enum {
GP2_set_precision,
GP2_set_w,
GP2_setios_flags_,
GP2_string_,
GP2_unknown_,
GP2_format_N
} GP2_type;
const char GP2_format[GP2_format_N + 1][1];
static int GP2_get_type(const char *format) {
// candidate UB with pointer compare
if (format >= GP2_format[0] && format <= GP2_format[GP2_format_N]) {
return (int) (format - GP2_format[0]);
}
return GP2_format_N;
}
int main(void) {
printf("%d\n", GP2_get_type(GP2_format[1]));
printf("%d\n", GP2_get_type("Hello World")); // potential UB
return 0;
}
Output (as expected, yet potentially UB)
1
5
If you want to comply with the C Standard then your options are:
Perform individual == or != tests against each pointer in the target range
You could use a hash table or search tree or something to speed this up, if it is a very large set
Redesign your code to not require this check.
A "probably works" method would be to cast all of the values to uintptr_t and then do relational comparison. If the system has a memory model with absolute ordering then it should define uintptr_t and preserve that ordering; and if it doesn't have such a model then the relational compare idea never would have worked anyway.
This is not an answer to the stated question, but an answer to the underlying problem.
Unless I am mistaken, the entire problem can be avoided by making GP_format a string. This way the problem simplifies to checking whether a pointer points to within a known string, and that is not UB. (If it is, then using strchr() to find a character and compute its index in the string would be UB, which would be completely silly. That would be a serious bug in the standard, in my opinion. Then again, I'm not a language lawyer, just a programmer that tries to write robust, portable C. Fortunately, the standard states it's written to help people like me, and not compiler writers who want to avoid doing hard work by generating garbage whenever a technicality in the standard lets them.)
Here is a full example of the approach I had in mind. This also compiles with clang-3.5, since the newest GCC I have on the machine I'm currently using is version 4.8.4, which has no _Generic() support. If you use a different version of clang, or gcc, change the first line in the Makefile accordingly, or run e.g. make CC=gcc.
First, Makefile:
CC := clang-3.5
CFLAGS := -Wall -Wextra -std=c11 -O2
LD := $(CC)
LDFLAGS :=
PROGS := example
.PHONY: all clean
all: clean $(PROGS)
clean:
rm -f *.o $(PROGS)
%.o: %.c
$(CC) $(CFLAGS) -c $^
example: out.o main.o
$(LD) $^ $(LDFLAGS) -o $#
Next, out.h:
#ifndef OUT_H
#define OUT_H 1
#include <stdio.h>
typedef enum {
out_char,
out_int,
out_double,
out_FILE,
out_set_fixed,
out_set_width,
out_set_decimals,
out_count
} out_type;
extern const char out_formats[out_count + 1];
extern int outf(FILE *, ...);
#define out(x...) outf(stdout, x)
#define err(x...) outf(stderr, x)
#define OUT(x) _Generic( (x), \
FILE *: out_formats + out_FILE, \
double: out_formats + out_double, \
int: out_formats + out_int, \
char: out_formats + out_char ), (x)
#define OUT_END ((const char *)0)
#define OUT_EOL "\n", ((const char *)0)
#define OUT_fixed(x) (out_formats + out_set_fixed), ((int)(x))
#define OUT_width(x) (out_formats + out_set_width), ((int)(x))
#define OUT_decimals(x) (out_formats + out_set_decimals), ((int)(x))
#endif /* OUT_H */
Note that the above OUT() macro expands to two subexpressions separated by a comma. The first subexpression uses _Generic() to emit a pointer within out_formats based on the type of the macro argument. The second subexpression is the macro argument itself.
Having the first argument to the outf() function be a fixed one (the initial stream to use) simplifies the function implementation quite a bit.
Next, out.c:
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <errno.h>
#include "out.h"
/* out_formats is a string consisting of ASCII NULs,
* i.e. an array of zero chars.
* We only check if a char pointer points to within out_formats,
* if it points to a zero char; otherwise, it's just a normal
* string we print as-is.
*/
const char out_formats[out_count + 1] = { 0 };
int outf(FILE *out, ...)
{
va_list args;
int fixed = 0;
int width = -1;
int decimals = -1;
if (!out)
return EINVAL;
va_start(args, out);
while (1) {
const char *const format = va_arg(args, const char *);
if (!format) {
va_end(args);
return 0;
}
if (*format) {
if (fputs(format, out) == EOF) {
va_end(args);
return 0;
}
} else
if (format >= out_formats && format < out_formats + sizeof out_formats) {
switch ((out_type)(format - out_formats)) {
case out_char:
if (fprintf(out, "%c", va_arg(args, int)) < 0) {
va_end(args);
return EIO;
}
break;
case out_int:
if (fprintf(out, "%*d", width, (int)va_arg(args, int)) < 0) {
va_end(args);
return EIO;
}
break;
case out_double:
if (fprintf(out, fixed ? "%*.*f" : "%*.*e", width, decimals, (float)va_arg(args, double)) < 0) {
va_end(args);
return EIO;
}
break;
case out_FILE:
out = va_arg(args, FILE *);
if (!out) {
va_end(args);
return EINVAL;
}
break;
case out_set_fixed:
fixed = !!va_arg(args, int);
break;
case out_set_width:
width = va_arg(args, int);
break;
case out_set_decimals:
decimals = va_arg(args, int);
break;
case out_count:
break;
}
}
}
}
Note that the above lacks even OUT("string literal") support; it's quite minimal implementation.
Finally, the main.c to show an example of using the above:
#include <stdlib.h>
#include "out.h"
int main(void)
{
double q = 1.0e6 / 7.0;
int x;
out("Hello, world!\n", OUT_END);
out("One seventh of a million is ", OUT_decimals(3), OUT(q), " = ", OUT_fixed(1), OUT(q), ".", OUT_EOL);
for (x = 1; x <= 9; x++)
out(OUT(stderr), OUT(x), " ", OUT_width(2), OUT(x*x), OUT_EOL);
return EXIT_SUCCESS;
}
In a comment, chux pointed out that we can get rid of the pointer inequality comparisons, if we fill the out_formats array; then (assuming, just for paranoia's sake, we skip the zero index), we can use (*format > 0 && *format < out_type_max && format == out_formats + *format) for the check. This seems to work just fine.
I also applied Pascal Cuoq's answer on how to make string literals decay into char * for _Generic(), so this does support out(OUT("literal")). Here is the modified out.h:
#ifndef OUT_H
#define OUT_H 1
#include <stdio.h>
typedef enum {
out_string = 1,
out_int,
out_double,
out_set_FILE,
out_set_fixed,
out_set_width,
out_set_decimals,
out_type_max
} out_type;
extern const char out_formats[out_type_max + 1];
extern int outf(FILE *, ...);
#define out(x...) outf(stdout, x)
#define err(x...) outf(stderr, x)
#define OUT(x) _Generic( (0,x), \
FILE *: out_formats + out_set_FILE, \
double: out_formats + out_double, \
int: out_formats + out_int, \
char *: out_formats + out_string ), (x)
#define OUT_END ((const char *)0)
#define OUT_EOL "\n", ((const char *)0)
#define OUT_fixed(x) (out_formats + out_set_fixed), ((int)(x))
#define OUT_width(x) (out_formats + out_set_width), ((int)(x))
#define OUT_decimals(x) (out_formats + out_set_decimals), ((int)(x))
#endif /* OUT_H */
Here is the correspondingly modified implementation, out.c:
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <errno.h>
#include "out.h"
const char out_formats[out_type_max + 1] = {
[ out_string ] = out_string,
[ out_int ] = out_int,
[ out_double ] = out_double,
[ out_set_FILE ] = out_set_FILE,
[ out_set_fixed ] = out_set_fixed,
[ out_set_width ] = out_set_width,
[ out_set_decimals ] = out_set_decimals,
};
int outf(FILE *stream, ...)
{
va_list args;
/* State (also, stream is included in state) */
int fixed = 0;
int width = -1;
int decimals = -1;
va_start(args, stream);
while (1) {
const char *const format = va_arg(args, const char *);
if (!format) {
va_end(args);
return 0;
}
if (*format > 0 && *format < out_type_max && format == out_formats + (size_t)(*format)) {
switch ((out_type)(*format)) {
case out_string:
{
const char *s = va_arg(args, char *);
if (s && *s) {
if (!stream) {
va_end(args);
return EINVAL;
}
if (fputs(s, stream) == EOF) {
va_end(args);
return EINVAL;
}
}
}
break;
case out_int:
if (!stream) {
va_end(args);
return EINVAL;
}
if (fprintf(stream, "%*d", width, (int)va_arg(args, int)) < 0) {
va_end(args);
return EIO;
}
break;
case out_double:
if (!stream) {
va_end(args);
return EINVAL;
}
if (fprintf(stream, fixed ? "%*.*f" : "%*.*e", width, decimals, va_arg(args, double)) < 0) {
va_end(args);
return EIO;
}
break;
case out_set_FILE:
stream = va_arg(args, FILE *);
if (!stream) {
va_end(args);
return EINVAL;
}
break;
case out_set_fixed:
fixed = !!va_arg(args, int);
break;
case out_set_width:
width = va_arg(args, int);
break;
case out_set_decimals:
decimals = va_arg(args, int);
break;
case out_type_max:
/* This is a bug. */
break;
}
} else
if (*format) {
if (!stream) {
va_end(args);
return EINVAL;
}
if (fputs(format, stream) == EOF) {
va_end(args);
return EIO;
}
}
}
}
If you find a bug or have a suggestion, please let me know in the comments. I don't actually need such code for anything, but I do find the approach very interesting.

Syntax error before string constant

I am seeing "syntax error before string constant at line ' testFunction(45, UP),'"
#define UP "UP\0"
#define DOWN "DOWN\0"
#define testFunction(intensity, direction) \
{ \
.force = intensity, \
.direction = direction, \
}
struct configureObject {
int force;
char direction[7];
};
static const struct configureObject configureFiles[] =
{
testFunction(45, UP),
testFunction(46, DOWN),
};
in main()
printf("force: %d\n", configureFiles[0].force);
printf("direction: %s\n", configureFiles[0].direction);
printf("force: %d\n", configureFiles[1].force);
printf("direction: %s\n", configureFiles[1].direction);
There are no other compiler hints. What may be the reason for this error?
Thank you.
The problem is that you use direction for two different things in:
.direction = direction,
Both get substituted.
Try:
#define testFunction(intensity, dir) \
{ \
.force = intensity, \
.direction = dir, \
}
(This is just an illustration, there's probably a better name than dir.)

Resources