Using macros to generalise code for function calls - c

I'm writing C code which requires me to use multiple function calls of the same definition which differ only by single characters. Is there a way I can make a macro function which takes say a number and can insert these calls into my code for me where I call the macro given I know the numbers at compile time:
i.e.
#define call_pin_macro(X)
enable_pin#X();
do_thing_pin#X();
do_other_thing_pin#X();
.
.
void pin_function(void){
call_pin_macro(1);
call_pin_macro(2);
call_pin_macro(3);
}
Instead of:
void pin_function(void){
enable_pin1();
do_thing_pin1();
do_other_thing_pin1();
enable_pin2();
do_thing_pin2();
do_other_thing_pin2();
enable_pin3();
do_thing_pin3();
do_other_thing_pin3();
}
As a note I have looked at stringification (Hence the included #X's) in gcc however I cannot get the above code to compile which I get an error "error: '#' is not followed by a macro parameter". And it thus it seems this isn't exactly the functionality I am after. Thanks in advance.

In gcc you can do it like this:
#define call_pin_macro(X) \
enable_pin##X(); \
do_thing_pin##X(); \
do_other_thing_pin##X();
The double hash is the macro concatenation operator. You don't want to use stringify because that will put quotes around it.
The backslashes allow you to continue the macro over several lines.

Related

Defining a replacement for punctuators in C

Several days ago, someone told me that their keyboard is faulty, leaving them unable to type ( on their keyboard. The first thing that came to my mind, when writing C, was to either copy the character from somewhere and just paste it or to try to use preprocessor directive #define . Once I tried to use #define, I realised that gcc doesn't let me write something like #define OB ( and I pretty much understand why. Is it possible to write something similar to this and let me replace a punctuator using #define?
If there was a trigraph for ( I would suggest that. Otherwise your solution with a macro might work, but unfortunately when written in C or a header file it can not be parsed as you want it. However using gcc you can specify that macro directly using the -D option.
Example:
int main OB ) {
printf OB "Hello, world\n");
}
I can compile it using the following command: cc -o test test.c -DOB='('. I needed to add ' otherwise bash wouldn't accept that.
You can also use make adding the extra parameter to CPPFLAGS: CPPFLAGS+="-DOB='('" make test - again you need more quotes than usual otherwise all the shells would not understand unquoted (. Of course you can just add CPPFLAGS+=-DOB='(' directly to the Makefile.
Edit:
In fact you can still have a macro in code. But you have to tell gcc that ( is not a part of macro identifier. The following worked for me:
#define OB \
(
int main OB ) {
printf OB "Hello, world\n");
}

arguments to printf and g_print - many syntax ,same result

i saw the following kind of code :
g_print("%s\n",_("foo"));
i haven't seen this style of passing arguments to print function ,but then i tried these :
g_print("%s\n","foo");
g_print("%s\n",("foo"));
then i thought had something to do with gtk(i'm fairly new to it) , but then i tried the same thing with printf :
printf("%s\n",_("foo"));
printf("%s\n","foo");
printf("%s\n",("foo"));
and all the above do the same thing : print foo to stdout . So my question is does passing the argument as "foo" , _("foo") ,or ("foo") make any difference at all , or is any one syntactic sugar
for the others,both in the case of printf , as well as g_print ?
sorry if this turns out to be a duplicate question ,but i couldn't seem to put my finger on what i should have searched for exactly in the first place .
The _() is actually a C macro defined as:
#define _(x) some_func(x)
Don't confuse it with ("foo") or "foo". Both of these are same and are just C strings.
You are probably seeing some sort of gettext macro, such as the one described by the glib docs. A common source for these is including glib/gi18n.h directly or (most likely) indirectly.
Marks a string for translation, gets replaced with the translated
string at runtime.
That header file contains a few in this vein:
#define _(String) gettext (String)

What is the glibc GLRO macro?

I'm currently trying to understand how the glibc startup routines (__libc_start_main) process Elf Auxiliary vector types (auxv_t).
Browsing through the source code for glibc, I find references to some function named GLRO. In trying to track down the definition for this function, the closest I can find is
#define GLRO(x) _##x
When I search for "##x", all I find is other similar "#define" directives, which leaves me confused. What does this definition mean? Is "##x" some kind of compiler directive?
Kerrek SB's answer provides what it does, but not the macro's purpose. So here it is:
"The GLRO() macro is used to access global or local read-only data, see sysdeps/generic/ldsodefs.h."
Source: http://cygwin.com/ml/libc-help/2012-03/msg00006.html
This is a preprocessor macro.
You can see for yourself what it does by running the preprocessor. Just make a sample file, like this:
// foo.c
#include <some_glibc_header.h>
GLRO(hello)
Now run the preprocessor:
gcc -E foo.c
You'll see that the macro creates a new token by putting an underscore in front of the given token; in our example we obtain _hello. The ## preprocessor operator concatenates tokens.
#define GLRO(x) _##x
## is the token pasting operator and it concatenates its two operands.
e.g., a ## b yields ab and _ ## x yields _x.
So for example:
GLRO(my_symbol) = 0;
would result in:
_my_symbol = 0;

C compiler warning Unknown escape sequence '\.' using regex for c program

I am using regex to determine a command line argument has the .dat extension. I am trying the following regex:
#define to_find "^.*\.(dat)?"
For some reason I am getting the warning I stated in the title of this question. First, is this expression correct? I believe it is. Second, if it is correct, how can i get rid of this warning?
I am coding a c program in Xcode and the above #define is in my .h file.
Thanks!
The warning is coming from the C compiler. It is telling you that \. is not a known escape sequence in C. Since this string is going to a regex engine, you need to double-escape the slash, like this:
#define to_find "^.*\\.(dat)?"
This regex would match a string with an optional .dat extension, with dat being optional. However, the dot . is required. If you want the dot to be optional as well, put it inside the parentheses, like this: ^.*(\\.dat)?.
Note that you can avoid escaping the individual metacharacters by enclosing them in square brackets, like this:
#define to_find "^.*([.]dat)?"
You need
#define to_find "^.*\\.(dat)?"
Should do the trick as the \ needs to be escaped for C and not the benefit for regex at this stage

What kind of statements,keywords,arguments etc can span multiple lines,and what need "\" for this?

How to know what kind of "things" can span multiple lines in C code without needing a \ character at the end of the line?And what kind of "things" need the \?How to know that?For example, in the following code, if and printf() work fine if I split them up in multiple lines.
if
(2<5)
printf
("Hi");
But in the following code,printf() needs a \ ,else shows error:
printf("Hi \
");
Similarly,the following shows error without a \
char name[]="Alexander the \
great of Greece";
So please tell me how to know when to use the \ while spanning multiple lines in C code, and when we can do without it?I mean, like if works both with and without the \.
This is about a concept called 'tokens'. A token is source-program text that the compiler does not break down into component elements. Literals (42, "text"), variable names, keywords are tokens.
Endline escaping is important for string constants only because it breaks apart a token. In your first example line breaks don't split tokens. All whitespace symbols between tokens are ignored.
The exception is macro definitions. A macro definition is ended with line break, so you need to escape it. But macros are not C code.
If you want to break a string across lines, you can either use the \ as you have...
printf("Hello \
World");
Or, alternatively, you can terminate the string with a " and then start a new string on the next line with no punctuation...
printf("Hello "
"World");
To the best of my knowledge, the issue with lines applies in only two places... within a string and within a define..
#define MY_DEFINE(fp) \
fprintf( fp, "Hello "\
"World" );
In short, the \ character is telling the compiler this statement continues on the next line. However, C/C++ is not white-space dependent, so really the only place this would come up is on a statement that is expected to be on a single line... which would be a string or a define.
C does not depend on line feeds.
You could use line feeds anywhere you like, as well as just not using them at all.
This implies seeing string literals as one token.
But, as in real life: Too much or to few, both does make life difficult. Happyness is matter of balance ... :-)
Please note that lines starting with a # are not C code, but pre-processor instructions.

Resources