FAQ Database Discussion Community


C: Use #define to define an array size

c,arrays,c-preprocessor
I used to capture 5 seconds of data from an ADC which was sending samples at 125 SPS, this translated to having an array of size 5 * 125. In my code this looked like: #define SPS 125 #define TIME 5 char Samples[SPS * TIME]; Now, I would like to...

How to calculate string checksum using C preprocessor only?

c,string,hash,c-preprocessor
I need to get a string checksum or hash (or something equivalent) using just the C preprocessor, if possible. The use case is as follows: I'm doing error logging on an embedded device with very limited memory and cpu. I would like to define a LogError() macro which inserts hash(__FILE__)...

C preprocessor how it works

c,c-preprocessor
i have the following files (its pseudo code, and i know the define, undef is ugly, but i would need it for some project) if i compile those files and link them together - it seems to work - that in file3, file1 - MYVAL == 1 is it safe...

In which situation does this macro can cause an error?

c,macros,preprocessor,c-preprocessor
Consider the following macro #define SQ(x) ((x) * (x)); In which situation does this macro can cause an error?...

Preprocessor errors trying to build FVWM95

gcc,c-preprocessor
Trying to build fvwm95-2.0.43f I get the following errors: FvwmIconBox.c: In function 'myErrorHandler': FvwmIconMan.c:412:1: error: pasting "." and "res" does not give a valid preprocessing token OS is Debian, tried Wheezy and Jessie. My best guess is that this might just be a minor change to how gcc handles preprocessor...

How to suppress a 'missing termination character' warning in cpp?

c-preprocessor,ansi-c,picoblaze
I'm trying to use cpp (ANSI-C preprocessor) to preprocess some non ANSI-C files. These files contain assembly instruction in PicoBlaze syntax. PicoBlaze uses 'd to annotate the literal's radix. I would like to preprocess my files with cpp. I get several: <stdin>:228:163: warning: missing terminating ' character [enabled by default]...

What preprocessor define does -fopenmp provide?

c,openmp,c-preprocessor
I've got some code that can run with (or without) OpenMP - it depends on how the user sets up the makefile. If they want to run with OpenMP, then they just add -fopenmp to CFLAGS and CXXFLAGS. I'm trying to determine what preprocessor macro I can use to tell...

Can macros accept types?

objective-c,c,c-preprocessor
Unless my understanding is incorrect, the following macro int i; // for loop const char* ctype; // proprietary type string void** pool = malloc(sizeof(void*) * (nexpected - 1)); size_t poolc = 0; #define SET(type, fn) type* v = (pool[poolc++] = malloc(sizeof(type))); \ *v = (type) fn(L, i) #define CHECK(chr, type,...

Expanded from macro 'num' while printing it using printf by Clang compiler

c,gcc,macros,clang,c-preprocessor
Code: char *color_name[] = { "red", "blue", "green" }; #define color_num (sizeof(color_name)/sizeof(char*)) int main(){ printf("size %d \n",color_num); return 0; } It works fine with GCC 4.8.2 on Centos 7. But I got error running above program on mac which says: note:expanded from macro 'color_num' Compiler on my Mac: ……include/c++/4.2.1 Apple...

Is it possible to use the value of a define as part of an identifier?

c,c-preprocessor
Is it possible to include a pre-defined id in an identifier? The header: /* myfile.h */ #define func MYID##_func static void func() {} #undef func The c file: /* myfile.c */ #define MYID FOO #include "myfile.h" #undef MYID #define MYID BAR #include "myfile.h" #undef MYID /* check the functions exist...

How to print C-preprocessor variables like __LINE__ with mexErrMsgTxt() In Matlab MEX

c++,c,debugging,mex,c-preprocessor
For debugging Matlab-MEX, which can be quite a hassle, it would be nice to have better assertion capabilities. Following this question about mex-assertions, it is possible to define a preprocessor makro, that throws an error to Matlab and prints a string (can mostly replace mxAssert, which unfortunately crashes Matlab2011b). #define...

Expand macro value in the variable name

c,c-preprocessor
I have #define MACRO foo #define Code(m) \ m##Bar Code(MACRO) I would like this to be resolved as fooBar, but it is resolved as MACROBar. What I need to change the macro to be resolved by its value, not its name. ...

Understanding DEFER and OBSTRUCT macros

c++,c++11,macros,preprocessor,c-preprocessor
I created a small macro metaprogramming library that implements basic useful constructs such as REPEAT(times, x), IF(value, true, false), tuples, and more. Most of my implementations work by overloading macros based upon their variadic argument count or through a counter: // Example: #define REPEAT_0(x) #define REPEAT_1(x) x REPEAT_0(x) #define REPEAT_2(x)...

Implications of typedef void FOO vs. #define FOO void in function signatures [duplicate]

c++,c,typedef,c-preprocessor
This question already has an answer here: void, VOID, C and C++ 3 answers While going through some source code that heavily mixes C and C++, I came across the following (slightly modified to protect the work of the company, the meaning remains the same): /* * Typedefs of...

Make c++ macro2 containt quoted body of macro1

c++,gcc,c-preprocessor,qmake
I'm trying to make some kind of a simple system that calculates the number of builds, including this info in .rc file (for windows) and met the problem. Here it is: #define QUOTE(s) #s #define A 0,0,0,1 #define A_STR QUOTE(A) Expanding of A_STR: "A" but not "0,0,0,1" as I expected....

What is the difference between global variables and #define in c

c,global-variables,c-preprocessor
Whats the reason why there are 2 opportunities : global variables symbolic constants with #define ? So I know what #define does but I don't know what the difference in use is. Which situation do I must have thus I'm able to decide myself upon the right opportunitie? What is...

Width prefixes to string constants

c,c-preprocessor,c11
The latest version of the C standard provides for width prefixes to string constants e.g. u8"a" is a single preprocessing token. Does whether you get one or two preprocessing tokens depend on the exact letters in the prefix? E.g. is it the case that u9"a" is still two preprocessing tokens?...

How to avoid code bloat when using pthreads in C?

c,multithreading,pthreads,c-preprocessor
When writing threaded code in C, I first have to create some struct which includes all the arguments and a wrapper function. This leads to lots of code bloat and is not easy to read. See: struct some_function_args { int arg1; int arg2; int arg3; }; void some_function_wrapper(struct some_function_args* args)...

How does this macro dispatcher work?

c,c-preprocessor
I saw this mechanism to simulate macro overloading recently here . This is the code used for dispatching: #define macro_dispatcher(func, ...) \ macro_dispatcher_(func, VA_NUM_ARGS(__VA_ARGS__)) #define macro_dispatcher_(func, nargs) \ macro_dispatcher__(func, nargs) #define macro_dispatcher__(func, nargs) \ func ## nargs I don't understand how this works. Why does it need the third macro...

Extracting the number of digits in a macro constant at compile-time

c,c-preprocessor
I need to do some preprocessor magic. Assume that I have a global constant #define MAX_VALUE 99999 What I need to do is to extract the length of this constant in its decimal representation at compile-time. In other words, I don't want to have another constant #define MAX_VALUE_STRLEN 5 polluting...

Pointer in a function “expected expression before = token”

c,pointers,c-preprocessor
I try to learn using pointers in functions by "simply" counting a circle. i get the error expected expression before '=' token but cant understand why. saying expected expression before.. is unclear to me, what kind of? #define PI = 3.1415f void circle(float *wert) { *wert = ( (*wert) *...

C++ on Linux - How do I #define a #ifdef / #endif debug conditional

c++,debugging,logging,c-preprocessor
I want to trace my code if DEBUG is defined, as in the following #ifdef code block: #ifdef DEBUG OP_LOG(debug) << "SEQUENCE: " __FILE__ << "::" << __FUNCTION__; #endif Someone said I could use a #define so that the above three lines would only be one line instead. This is...

How to determine if C11 _Generic is supported by the compiler using preprocessor directives?

generics,keyword,c-preprocessor,language-features,c11
I would like to know if there is any way to determine if support for _Generic type-generic macros can be determined for a given compiler using preprocessor directives such as: #if __C11_GENERIC_IS_SUPPORTED__ == 1 Any help would be appreciated......

Variable declaration via macro into inline function

c,inline,declaration,c-preprocessor
I have just a fast question. I use this macro to create new array: #define NEW_ARRAY(id,size) int id[size]={0,} Can I make a inline function that does same thing? (without malloc, I need swap between macros and inlines with conditional compilation without changing a source code) I assume it isn't possible,...

Best way to deal with a trailing comma when using X macros in C++

c++,c++11,c++14,c-preprocessor
What's the best way to deal with extra trailing commas when working with X macros? Specifically, I have the following setup in a file test01.cpp struct Foo { #define X(name,val) int name; #include "test01.def" #undef X Foo() : #define X(name,val) name(val), #include "test01.def" #undef X {} }; int main(){ Foo...

Is the declaration of a variable name in a #define directive well defined?

c,c-preprocessor,variable-declaration
If I had the following code: #include <stdio.h> #define VAR_NAME a_variable int VAR_NAME = 42; int main() { printf("%i\n", VAR_NAME); printf("%i\n", a_variable); a_variable = 123; printf("%i\n", VAR_NAME); printf("%i\n", a_variable); return 0; } Is the declaration of a_variable well defined? On my system, an int named a_variable is declared, but do...

Which -x to use for preprocessing through GCC?

gcc,c-preprocessor
I need to use GCC (4.8.1 in my case) to run the preprocessor on a file which contains preprocessor directives, but not (necessarily) C/C++ code. These directives can depend on GCC's pre-defined macros, so I have to invoke the preprocessor through GCC instead of directly. I know that I can...

Once-only pseudo-generic header in C

c,templates,generics,header-files,c-preprocessor
After some work on the generic vector I asked about on this question, I would like to know if there is any way of checking that each instanciation of the library is only done once per type. Here is what the current header file looks like: #ifndef VECTOR_GENERIC_MACROS #define VECTOR_GENERIC_MACROS...

Is there an equivalent of Haskell's `let`/`in` in C Preprocessor Macros?

c,c-preprocessor
I have a function as follows (used in a prime seive, in case you're curious) unsigned long long primeAt(unsigned long long index) { return index * 3 + (index % 2 ? 2 : 1); } which I have refactored into the macro #define PRIME_AT(index) (index * 3 + (index...

What is ## syntax? [duplicate]

c++,c-preprocessor
This question already has an answer here: What does ## mean in the #define directive in the code here 1 answer I read through some sample code, and caught up with this ## syntax that I have never seen before. The code sample as following: #define DEF_MAKE_BT_1_COMP(BT)\ inline i_##BT...

Stopping macro expansion

c,c-preprocessor
I have a problem with macro expansion deferral. Here is an example: #include <stdio.h> #define CONST_ABC 15 #define CONST_5 7 #define ABC 5 #define PRINT(x) printf("CONST=%d\n", CONST_ ## x) // The problematic macro #define PRINT2(x) PRINT(x) int main(int argc, char *argv[]) { PRINT(ABC); // Prints 15 - OK PRINT2(ABC); //...

Macro Syntax Confusion

c,macros,c-preprocessor
I have gone through the concepts of macros but never encountered #define reg_add_cfghwmod_beacon_led_control(a,b) \ _reg_add_cfghwmod_beacon_led_control(a) This kind of syntax can any one explain me what the above macro means....

Extract Argument from C Macro

c,macros,arguments,c-preprocessor
I have a number of definitions consisting of two comma-separated expressions, like this: #define PIN_ALARM GPIOC,14 I want to pass the second expression of those definitions (14 in the case above) to unary macros like the following: #define _PIN_MODE_OUTPUT(n) (1U << ((n) * 2U)) How can I extract the second...

Quote macro for defining string

c,c-preprocessor
Is it possible to quote the "content" of a macro? Something like the following code for printing the string "AAA". #include <stdio.h> #include <stdlib.h> #define _L 5 #define _QUOTE(a) #a #define _TEXT AAA #define _STRINGAAA _QUOTE(_TEXT) const char STRINGAAA[ _L ] = _STRINGAAA; int main(void) { printf( "%s\n", STRINGAAA );...

Is there a way to use the preprocessor to generate an operator like + or - from ascii number for symbol, without including that symbol?

c,c-preprocessor
So I am trying to obfuscate some c code, and I'm wondering if there is a way to generate an operator like & (for address), or + or - (for addition/subtraction) etc, from it's hex/octal/decimal code in ascii, without resorting to some sort of table or something that includes the...

How to define an extern function in multiple files and specify which definition to use?

c++,c-preprocessor
Not sure if extern is the correct way to handle this situation, but it is what I've currently attempted. I have a library sharing common code across multiple projects, some of which have different pin configuration that must be done during the _system_pre_init() function in the library (which is called...

How to insert preprocessor value in a vector?

c++,stl,c-preprocessor
#define HEADER = 5 int _tmain(int argc, _TCHAR* argv[]) { vector<int> v; v.push_back(HEADER); return 0; } why this code gives me a syntex error ? as far as i preprocessor get treated like int....

#define a tuple in C

c,c-preprocessor,avr
I want to be able to define a tuple which represents the arguments needed by other macros. I think the best way to show what I want is to show an example: #include <avr/io.h> #define LED_PORT PORTB #define LED_DDR DDRB #define LED_PIN PB7 #define LED LED_PORT, LED_DDR, LED_PIN #define OUTPUT(port,...

How to hide extra output from #pragma message

gcc,c-preprocessor,pragma
I'm currently porting some code to a new platform and toolchain, which includes an upgrade from gcc 4.7.2 to gcc 4.9.2 (or more specifically, from release 2012 to 2014 of the OSELAS toolchains - I've also reproduced the behavior on my host machine with gcc 4.6.4 (works) and gcc 4.8.3...

Assignment macro writing

c,c-preprocessor
I am trying to write a macro for the following repeated code inside the for loop. for(i=0; i<n; i++) { a->x = b->x; a->y = b->y; a->z = b->z; } for(j=0;j<n;j++){ a->x = c->x; a->y = c->y; a->z = c->z; } --------- with macro #define COPY(x,y,z) \ a->x = x;\...

Is it possible create a “variable” header guard name in C?

c,header,c-preprocessor
fellow programmers, I'm new to the C preprocessor and have been recently trying to create a generic-like library in C (as an exercise), and I've come upon a little problem when creating header guards. All the preprocessor macros are set up so I can include and use my headers like...

Statement in C++ macro

c++,c,macros,c-preprocessor
Reading chromium code, found helpful macro for handling EINTR errno of system calls on POSIX compliant systems. Here are the code(base/posix/eintr_wrapper.h): #define HANDLE_EINTR(x) ({ \ decltype(x) eintr_wrapper_result; \ do { \ eintr_wrapper_result = (x); \ } while (eintr_wrapper_result == -1 && errno == EINTR); \ eintr_wrapper_result; \ }) The question...

Concatenation and the standard

c++,c++11,preprocessor,c-preprocessor
According to this page "A ## operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers". That is, the preprocessor operator ## acts on identifiers. Microsoft's page says ", each occurrence of the token-pasting operator in token-string is removed, and the tokens preceding and...

Passing an initialization list to a macro

c++,c++11,c-preprocessor
Why doesn't the commented out line in the following program compile? #include <iostream> #include <vector> using namespace std; #define F1(a) 1 int F2(vector<int>) { return 2; } int main() { vector<int> v; v = vector<int>{1,2,3}; cout << F1( v ) << endl; //The following line doesn't compile. The error is:...

C find static array size (preventing mistakes)

c,arrays,c-preprocessor
Finding the size of a static array is a common operation. see: C find static array size - sizeof(a) / sizeof((a)[0]) This can be wrapped into a macro, eg: #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) however its possible to accidentally pass in a regular pointer. eg: void func(SomeArray **foo) { int...

C++ preprocessor test if class member exists

c++,c-preprocessor
Is there an equivalent of #ifdef to test if a member exists in a class so that processing can be done without causing the code to fail the compiler. I have tried template operations but the particular problem has not succeeded. For example #if member baseclass.memberA() baseclass.memberA().push_back(data); #else doAlternate(data); #endif...

c++ from macros to templates

c++,templates,macros,concatenation,c-preprocessor
I'm trying to change some macros (we have a bunch of them) for function templates. Many times, I have the following scenario: #include <iostream> void function_A( void ) { std::cout << "function A" << std::endl; } void function_B( void ) { std::cout << "function B" << std::endl; } #define FOO(...

syntax error : missing ')' before 'constant'

c,compiler-errors,macros,syntax-error,c-preprocessor
I have some syntax problems that I don't know how to fix. I'm trying to build some functions to matrix, can someone help me resolve those problems? 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143: syntax error : missing ')' before 'constant' 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143:...

Expanding / Recombining macro tuple

c++,c,c-preprocessor
I'm trying to do something like the following with macros in C++: #define ESC(...) __VA_ARGS__ #define f1(a,b,c) {a:b:c} #define f2(ab,c) ( ESC ab,c ) #define f3(ab,c) f1( ESC f2( ab, c ) ) f2((myA,myB),myC) // RESULT: (myA,myB,myC) f3((myA,myB),myC) // DESIRED RESULT: {myA:myB:myC} In other words, I have a set of...

How does #if macro work in C?

c,macros,c-preprocessor
MyMacros.h: int const TESTING = 1; #define INFO(MSG) fprintf(stderr, "INFO :: %s\n", MSG); MyProgram.c: #if TESTING INFO("File 'data.dat' opened correctly."); #endif The message isn't printed to the screen. However if I do this: #if TESTING < 1 It works and prints the message. Hunh???...

Equivalent to Interfaces in Embbeded C / Code organization

c,architecture,preprocessor,c-preprocessor
I'm developing embedded C code on EFM32 Cortex M3 processors, and after a few months the code is beginning to get crazy... By this I mean that we changed the hardware so we get different versions, on which we changed some components, moved some IOs, have different states for theses...

Build with different values in c++ Eclipse CDT

c++,linux,eclipse,c-preprocessor,cdt
How can I do this in c++/Eclipse CDT ? #if BUILD = DEBUG #define DB_FILE="DB" #elif BUILD = RELEASE #define DB_FILE="/home/project/clientXY.DB" .... Is there any configuration option in CDT that I can modify between the builds (to change the above parameters)? many thanks in advance :D...

C Preprocessor generate macros by concatenation and stringification [duplicate]

c,concatenation,c-preprocessor,stringification
This question already has an answer here: What are the applications of the ## preprocessor operator and gotchas to consider? 13 answers I have a set of target macros for which I want to generate aliases based on a choosing macro, like so: Choosing macro: #define I2C_MODULE 1 Alias...