My machine has CRTSCTS #defined inside a #ifdef __USE_MISC which stops it being available to C programs which I compile.
/usr/include/x86_64-linux-gnu/bits/termios.h:
...
#define B4000000 0010017
#define __MAX_BAUD B4000000
#ifdef __USE_MISC
# define CIBAUD 002003600000 /* input baud rate (not used) */
# define CMSPAR 010000000000 /* mark or space (stick) parity */
# define CRTSCTS 020000000000 /* flow control */
#endif
/* c_lflag bits */
#define ISIG 0000001
#define ICANON 0000002
...
How do I get access to CRTSCTS without just hacking the value 020000000000 into my program?
I already #include <termios.h> and many other headers.
I am also using:
#define __USE_POSIX199309
#define _POSIX_C_SOURCE 199309L
#include <time.h> /* nanosleep needs lines above */
The __USE_MISC macro is an internal definition that, though I suppose you could define this yourself, it's better to find the proper feature-test macro that enables it.
On my CentOS 7 system, /usr/include/features.h has a whole range of these kinds of macros, and it appears that __USE_MISC is enabled by _BSD_SOURCE or _SVID_SOURCE; it's not clear which one is compatible with other things you're going to need.
... // features.h
#if defined _BSD_SOURCE || defined _SVID_SOURCE
# define __USE_MISC 1
#endif
Try #define _BSD_SOURCE at the top of your program - before all the includes - and see how it goes.
Ref: http://man7.org/linux/man-pages/man7/feature_test_macros.7.html
Related
I write a bootloader for an AVR XMega Microcontroller and the bootloader got configured by a configuration file:
Config_Bootloader.h
#ifndef CONFIG_BOOTLOADER_H_
#define CONFIG_BOOTLOADER_H_
#include <avr/io.h>
#define BOOTLOADER_INTERFACE &USARTE0
#define BOOTLOADER_BAUD 115200
#define BOOTLOADER_TX 3
#endif /* CONFIG_BOOTLOADER_H_ */
This configuration file is should be preprocessed by another include file to get some register values etc.
Bootloader_Preprocessing.h
#ifndef BOOTLOADER_PREPROCESSING_H_
#define BOOTLOADER_PREPROCESSING_H_
#include <avr/io.h>
#ifdef USARTE0
#if(BOOTLOADER_INTERFACE == &USARTE0)
#define BOOTLOADER_PORT &PORTE
#else
#error "Invalid bootloader interface!"
#endif
#endif
#if(BOOTLOADER_BAUD == 9600)
#define BOOTLOADER_BRREG_VALUE 12
#define BOOTLOADER_SCALE_VALUE 0
#elif(BOOTLOADER_BAUD == 19200)
#define BOOTLOADER_BRREG_VALUE 11
#define BOOTLOADER_SCALE_VALUE -1
#elif(BOOTLOADER_BAUD == 38400)
#define BOOTLOADER_BRREG_VALUE 9
#define BOOTLOADER_SCALE_VALUE -2
#elif(BOOTLOADER_BAUD == 57600)
#define BOOTLOADER_BRREG_VALUE 75
#define BOOTLOADER_SCALE_VALUE -6
#elif(BOOTLOADER_BAUD == 115200)
#define BOOTLOADER_BRREG_VALUE 11
#define BOOTLOADER_SCALE_VALUE -7
#else
#error "Invalid baud rate for bootloader!"
#endif
#endif /* BOOTLOADER_PREPROCESSING_H_ */
I include both files into my Bootloader.h
#ifndef BOOTLOADER_H_
#define BOOTLOADER_H_
#include "Config_Bootloader.h"
#include "Bootloader_Preprocessing.h"
#endif /* BOOTLOADER_H_ */
And I get this errors and warnings:
> #define BOOTLOADER_INTERFACE &USARTE0
operator '&' has no left operand
> #if(BOOTLOADER_INTERFACE == &USARTE0)
in expansion of macro 'BOOTLOADER_INTERFACE'
#error "Invalid bootloader interface!"
So why does the compare of the address doesn´t work?
There is no such thing as an "address" in the preprocessor, therefore they cannot be compared in an #if preprocessor instruction.
See the GCC docs for #IF for details on what it can and can't do. Consult the documentation for the preprocessor you are using, additional/different restrictions may apply (you tagged this as AVR).
It seems that your preprocessor concluded that the operator & has to be the bitwise operator &, which is a binary operator and therefore requires a left operand.
Okay, I have a solution after struggeling with the C preprocessor.
I define the symbol BOOTLOADER_INTERFACE=E,0 in my config and process the input:
#define CATENATE(Prefix, Name) Prefix##Name
#define FIRST_ARG(A, B) A
#define SECOND_ARG(A, B) B
#define MAKE_USART_NAME(Uart) CATENATE(USART, Uart)
#define MAKE_PORT_NAME(Port) CATENATE(PORT, Port)
#define USART_NAME(Name) MAKE_USART_NAME(CATENATE(Name))
#define PORT_NAME(Name) MAKE_PORT_NAME(FIRST_ARG(Name))
The result is the address of the PORT- and USART-Structure, depending on the given USART interface.
I'm working on some geometry-based code. The task at hand involves use of a bounding-box to contain the solid specimen. Now, in the code I have devised two different types of such boxes, namely INNER_BOUNDING_BOX and OUTER_BOUNDING_BOX. The code further expects use of any one of the two boxes, but not both. I'm trying to achieve it through the use of preprocessor.
I have written further code based on a couple of macros namely USE_INNER_BOUNDING_BOX and USE_OUTER_BOUNDING_BOX. I can ensure that at any time any one macro is defined through some simple construct like this:
#if defined(USE_INNER_BOUNDING_BOX) && defined(USE_OUTER_BOUNDING_BOX)
#undef USE_INNER_BOUNDING_BOX
#undef USE_OUTER_BOUNDING_BOX
#define USE_INNER_BOUNDING_BOX
#endif
#ifndef USE_INNER_BOUNDING_BOX
#ifndef USE_OUTER_BOUNDING_BOX
#define USE_INNER_BOUNDING_BOX
#endif
#endif
Now, if I wanted to use any particular box, I could just define the corresponding macro. The difficulty comes with wanting for use of a default setting macro say USE_DEFAULT_BOUNDING_BOX, which I could use to then set up define for any one of USE_INNER_BOUNDING_BOX or USE_OUTER_BOUNDING_BOX when both or none of them are explicitly defined.
I'd be inclined towards portable code, but compiler-specific trick could also pass. I'm using Visual Studio 2012.
Reliable one-of-many selections like those can better be done by selecting them with a single multi-value switch right away.
#define BOUNDING_INNER 1
#define BOUNDING_OUTER 2
/* default */
#define BOUNDING_BOX_TO_USE BOUNDING_INNER
/* alternatively please activate below line
#define BOUNDING_BOX_TO_USE BOUNDING_OUTER
*/
If you need to stay backward compatible to some configurations,
e.g. your code has already been used by others,
you can derive the single switch from the two, matching your default behaviour.
The advantage is to avoid #undef (in case you agree that it is an advantage to do so).
#if defined(USE_INNER_BOUNDING_BOX) && defined(USE_OUTER_BOUNDING_BOX)
#define BOUNDING_BOX_TO_USE BOUNDING_INNER
#endif
#ifndef USE_INNER_BOUNDING_BOX
#ifndef USE_OUTER_BOUNDING_BOX
#define BOUNDING_BOX_TO_USE BOUNDING_INNER
#endif
#endif
/* In case you are as paranoid a programmer as I am,
you might want to do some plausibility checking
here. ifndef, >0, <2 etc., triggering some #errors. */
/* Later, in code doing the actual implementation: */
#if (BOUNDING_BOX_TO_USE == BOUNDING_INNER)
/* do inner bounding stuff */
#endif
/* other code, e.g. common for inner and outer */
#if (BOUNDING_BOX_TO_USE == BOUNDING_OUTER)
/* do outer bounding stuff */
#endif
Since there are only two values I would use only one boolean variable:
#ifndef USE_OUTER_BOUNDING_BOX
#define USE_OUTER_BOUNDING_BOX 0
#endif
If USE_OUTER_BOUNDING_BOX is zero (false) the inner bounding box is used.
test.c:
#include <stdio.h>
#ifndef USE_OUTER_BOUNDING_BOX
#define USE_OUTER_BOUNDING_BOX 0
#endif
int main(void)
{
printf("%d\n", USE_OUTER_BOUNDING_BOX);
return 0;
}
Example:
$ cc -o test -DUSE_OUTER_BOUNDING_BOX=0 test.c
$ ./test
0
$ cc -o test -DUSE_OUTER_BOUNDING_BOX=1 test.c
$ ./test
1
Here is what I ended with:
// Comment to use bigger outer Bounding-Box
#define USE_INNER_BOUNDING_BOX
#define INNER_BOUNDING_BOX 0
#define OUTER_BOUNDING_BOX 1
#define DEFAULT_BOUNDING_BOX OUTER_BOUNDING_BOX
#if defined(USE_INNER_BOUNDING_BOX) && !defined(USE_OUTER_BOUNDING_BOX)
#define USE_BOUNDING_BOX INNER_BOUNDING_BOX
#elif defined(USE_OUTER_BOUNDING_BOX)
#define USE_BOUNDING_BOX OUTER_BOUNDING_BOX
#else
#define USE_BOUNDING_BOX DEFAULT_BOUNDING_BOX
#endif
#if (USE_BOUNDING_BOX == INNER_BOUNDING_BOX)
#undef USE_OUTER_BOUNDING_BOX
#define USE_INNER_BOUNDING_BOX
#else
#undef USE_INNER_BOUNDING_BOX
#define USE_OUTER_BOUNDING_BOX
#endif
This just works in this case. In case of more boxes, I'd append the conditional blocks.
I came across some C code where the author uses the following idiom all over the place:
typedef __int32 FOO_INT32;
#define FOO_INT32 FOO_INT32
What is the point of doing this? Shouldn't the typedef be enough? It is a workaround for some wonky C compilers out there?
With the #define instruction, you'll then be able to test if the typedef has been done somewhere else in the code using :
#ifdef FOO_INT32
FOO_INT32 myfoo;
#else
int myfoo;
#endif
It's a practice that's sometimes done in headers. The #define allows for compile-time testing of the existence of the typedef. This allows code like:
#ifdef FOO_INT32
FOO_INT32 myfoo;
#else
int myfoo;
#endif
or as a true guard #define, similar to header file guards.
#ifndef FOO_INT32
typedef int FOO_INT32
#define FOO_INT32 FOO_INT32
#endif
It's not necessarily a good practice, but it has its uses, especially when you have some headers which use types defined by other libraries, but you want to provide your own substitutes for cases when you're not using those libraries at all.
Another reason is that a standard might require definitions to be macros.
Snippet from glibc netinet/in.h:
/* Standard well-defined IP protocols. */
enum
{
IPPROTO_IP = 0, /* Dummy protocol for TCP. */
#define IPPROTO_IP IPPROTO_IP
IPPROTO_ICMP = 1, /* Internet Control Message Protocol. */
#define IPPROTO_ICMP IPPROTO_ICMP
IPPROTO_IGMP = 2, /* Internet Group Management Protocol. */
#define IPPROTO_IGMP IPPROTO_IGMP
Here enum symbols are also exported as macros as required by the relevant POSIX spec, quoting:
The header shall define the following macros for use as
values of the level argument of getsockopt() and setsockopt():
IPPROTO_IP
Internet protocol.
IPPROTO_IPV6
Internet Protocol Version 6.
...
This pattern is also useful for feature-detection of registers in microprocessors, as in this question. For instance, there may be two similar header files, one of which defines one timer, and one that defines 2:
cheapprocessor.h:
#define TMR1 TMR1
extern volatile int TMR1;
expensiveprocessor.h:
#define TMR1 TMR1
extern volatile int TMR1;
#define TMR2 TMR2
extern volatile int TMR2;
Which means in your main code, when you include a generic processor.h that delegates to the appropriate header for the target, you can detect features:
#include <processor.h>
#ifdef TMR2
x = TMR2;
#else
x = 0; // no timer, probably because we're on the cheaper model
#endif
I'm trying to write a portable program that deals with ustar archives. For device files, these archives store the major and minor device numbers. However, the struct stat as laid out in POSIX only contains a single st_rdev member of type dev_t described with “Device ID (if file is character or block special).”
How can I convert between a pair of major and minor device numbers and a single st_rdev member as returned by stat() in a portable manner?
While all POSIX programming interfaces use the device number (of type dev_t) as is, FUZxxl pointed out in a comment to this answer that the common UStar file format -- most common tar archive format -- does split the device number into major and minor. (They are typically encoded as seven octal digits each, so for compatibility reasons one should limit to 21-bit unsigned major and 21-bit unsigned minor. This also means that mapping the device number to just the major or just the minor is not a reliable approach.)
The following include file expanding on Jonathon Reinhart's answer, after digging on the web for the various systems man pages and documentation (for makedev(), major(), and minor()), plus comments to this question.
#if defined(custom_makedev) && defined(custom_major) && defined(custom_minor)
/* Already defined */
#else
#undef custom_makedev
#undef custom_major
#undef custom_minor
#if defined(__linux__) || defined(__GLIBC__)
/* Linux, Android, and other systems using GNU C library */
#ifndef _BSD_SOURCE
#define _BSD_SOURCE 1
#endif
#include <sys/types.h>
#define custom_makedev(dmajor, dminor) makedev(dmajor, dminor)
#define custom_major(devnum) major(devnum)
#define custom_minor(devnum) minor(devnum)
#elif defined(_WIN32)
/* 32- and 64-bit Windows. VERIFY: These are just a guess! */
#define custom_makedev(dmajor, dminor) ((((unsigned int)dmajor << 8) & 0xFF00U) | ((unsigned int)dminor & 0xFFFF00FFU))
#define custom_major(devnum) (((unsigned int)devnum & 0xFF00U) >> 8)
#define custom_minor(devnum) ((unsigned int)devnum & 0xFFFF00FFU)
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
/* FreeBSD, OpenBSD, NetBSD, and DragonFlyBSD */
#include <sys/types.h>
#define custom_makedev(dmajor, dminor) makedev(dmajor, dminor)
#define custom_major(devnum) major(devnum)
#define custom_minor(devnum) minor(devnum)
#elif defined(__APPLE__) && defined(__MACH__)
/* Mac OS X */
#include <sys/types.h>
#define custom_makedev(dmajor, dminor) makedev(dmajor, dminor)
#define custom_major(devnum) major(devnum)
#define custom_minor(devnum) minor(devnum)
#elif defined(_AIX) || defined (__osf__)
/* AIX, OSF/1, Tru64 Unix */
#include <sys/types.h>
#define custom_makedev(dmajor, dminor) makedev(dmajor, dminor)
#define custom_major(devnum) major(devnum)
#define custom_minor(devnum) minor(devnum)
#elif defined(hpux)
/* HP-UX */
#include <sys/sysmacros.h>
#define custom_makedev(dmajor, dminor) makedev(dmajor, dminor)
#define custom_major(devnum) major(devnum)
#define custom_minor(devnum) minor(devnum)
#elif defined(sun)
/* Solaris */
#include <sys/types.h>
#include <sys/mkdev.h>
#define custom_makedev(dmajor, dminor) makedev(dmajor, dminor)
#define custom_major(devnum) major(devnum)
#define custom_minor(devnum) minor(devnum)
#else
/* Unknown OS. Try a the BSD approach. */
#ifndef _BSD_SOURCE
#define _BSD_SOURCE 1
#endif
#include <sys/types.h>
#if defined(makedev) && defined(major) && defined(minor)
#define custom_makedev(dmajor, dminor) makedev(dmajor, dminor)
#define custom_major(devnum) major(devnum)
#define custom_minor(devnum) minor(devnum)
#endif
#endif
#if !defined(custom_makedev) || !defined(custom_major) || !defined(custom_minor)
#error Unknown OS: please add definitions for custom_makedev(), custom_major(), and custom_minor(), for device number major/minor handling.
#endif
#endif
One could glean additional definitions from existing UStar-format -capable archivers. Compatibility with existing implementations on each OS/architecture is, in my opinion, the most important thing here.
The above should cover all systems using GNU C library, Linux (including Android), FreeBSD, OpenBSD, NetBSD, DragonFlyBSD, Mac OS X, AIX, Tru64, HP-UX, and Solaris, plus any that define the macros when <sys/types.h> is included. Of the Windows part, I'm not sure.
As I understand it, Windows uses device 0 for all normal files, and a HANDLE (a void pointer type) for devices. I am not at all sure whether the above logic is sane on Windows, but many older systems put the 8 least significant bits of the device number into minor, and the next 8 bits into major, and the convention seems to be that any leftover bits would be put (without shifting) into minor, too. Examining existing UStar-format tar archives with references to devices would be useful, but I personally do not use Windows at all.
If a system is not detected, and the system does not use the BSD-style inclusion for defining the macros, the above will error out stopping the compilation. (I would personally add compile-time machinery that could help finding the correct header definitions, using e.g. find, xargs, and grep, in case that happens, with a suggestion to send the addition upstream, too. touch empty.h ; cpp -dM empty.h ; rm -f empty.h should show all predefined macros, to help with identifying the OS and/or C library.)
Originally, POSIX stated that dev_t must be an arithmetic type (thus, theoretically, it might have been some variant of float or double on some systems), but IEEE Std 1003.1, 2013 Edition says it must be an integer type. I would wager that means no known POSIX-y system ever used a floating-point dev_t type. It would seem that Windows uses a void pointer, or HANDLE type, but Windows is not POSIX-compliant anyway.
Use the major() and minor() macros after defining BSD_SOURCE.
The makedev(), major(), and minor() functions are not specified in
POSIX.1, but are present on many other systems.
http://man7.org/linux/man-pages/man3/major.3.html
I have a program based on an antique version of ls for Minix, but much mangled modified by me since then. It has the following code to detect the major and minor macros — and some comments about (now) antique systems where it has worked in the past. It assumes a sufficiently recent version of GCC is available to support #pragma GCC diagnostic ignored etc. You have to be trying pretty hard (e.g. clang -Weverything) to get the -Wunused-macros option in effect unless you include it explicitly.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-macros"
/* Defines to ensure major and minor macros are available */
#define _DARWIN_C_SOURCE /* In <sys/types.h> on MacOS X */
#define _BSD_SOURCE /* In <sys/sysmacros.h> via <sys/types.h> on Linux (Ubuntu 12.0.4) */
#define __EXTENSIONS__ /* Maybe beneficial on Solaris */
#pragma GCC diagnostic pop
/* From Solaris 2.6 sys/sysmacros.h
**
** WARNING: The device number macros defined here should not be used by
** device drivers or user software. [...] Application software should make
** use of the library routines available in makedev(3). [...] Macro
** routines bmajor(), major(), minor(), emajor(), eminor(), and makedev()
** will be removed or their definitions changed at the next major release
** following SVR4.
**
** #define O_BITSMAJOR 7 -- # of SVR3 major device bits
** #define O_BITSMINOR 8 -- # of SVR3 minor device bits
** #define O_MAXMAJ 0x7f -- SVR3 max major value
** #define O_MAXMIN 0xff -- SVR3 max major value
**
** #define L_BITSMAJOR 14 -- # of SVR4 major device bits
** #define L_BITSMINOR 18 -- # of SVR4 minor device bits
** #define L_MAXMAJ 0x3fff -- SVR4 max major value
** #define L_MAXMIN 0x3ffff -- MAX minor for 3b2 software drivers.
** -- For 3b2 hardware devices the minor is restricted to 256 (0-255)
*/
/* AC_HEADER_MAJOR:
** - defines MAJOR_IN_MKDEV if found in sys/mkdev.h
** - defines MAJOR_IN_SYSMACROS if found in sys/macros.h
** - otherwise, hope they are in sys/types.h
*/
#if defined MAJOR_IN_MKDEV
#include <sys/mkdev.h>
#elif defined MAJOR_IN_SYSMACROS
#include <sys/sysmacros.h>
#elif defined(MAJOR_MINOR_MACROS_IN_SYS_TYPES_H)
/* MacOS X 10.2 - for example */
/* MacOS X 10.5 requires -D_DARWIN_C_SOURCE or -U_POSIX_C_SOURCE - see above */
#elif defined(USE_CLASSIC_MAJOR_MINOR_MACROS)
#define major(x) ((x>>8) & 0x7F)
#define minor(x) (x & 0xFF)
#else
/* Hope the macros are in <sys/types.h> or otherwise magically visible */
#endif
#define MAJOR(x) ((long)major(x))
#define MINOR(x) ((long)minor(x))
You will justifiably not be all that keen on the 'hope the macros are … magically visible' part of the code.
The reference to AC_HEADER_MAJOR is to the macro in the autoconf that deduces this information. It would be relevant if you have a config.h file generated by autoconf.
POSIX
Note that the POSIX pax command defines the ustar format and specifies that it includes devmajor and devminor in the information, but adds:
… Represent character special files and block special files respectively. In this case the devmajor and devminor fields shall contain information defining the device, the format of which is unspecified by this volume of POSIX.1-2008. Implementations may map the device specifications to their own local specification or may ignore the entry.
This means that there isn't a fully portable way to represent the numbers. This is not wholly unreasonable (but it is a nuisance); the meanings of the major and minor device numbers varies across platforms and is unspecified too. Any attempt to create block or character devices via ustar format will only work reasonably reliably if the source and target machines are running the same (version of the same) operating system — though usually they're portable across versions of the same operating system.
I came across some C code where the author uses the following idiom all over the place:
typedef __int32 FOO_INT32;
#define FOO_INT32 FOO_INT32
What is the point of doing this? Shouldn't the typedef be enough? It is a workaround for some wonky C compilers out there?
With the #define instruction, you'll then be able to test if the typedef has been done somewhere else in the code using :
#ifdef FOO_INT32
FOO_INT32 myfoo;
#else
int myfoo;
#endif
It's a practice that's sometimes done in headers. The #define allows for compile-time testing of the existence of the typedef. This allows code like:
#ifdef FOO_INT32
FOO_INT32 myfoo;
#else
int myfoo;
#endif
or as a true guard #define, similar to header file guards.
#ifndef FOO_INT32
typedef int FOO_INT32
#define FOO_INT32 FOO_INT32
#endif
It's not necessarily a good practice, but it has its uses, especially when you have some headers which use types defined by other libraries, but you want to provide your own substitutes for cases when you're not using those libraries at all.
Another reason is that a standard might require definitions to be macros.
Snippet from glibc netinet/in.h:
/* Standard well-defined IP protocols. */
enum
{
IPPROTO_IP = 0, /* Dummy protocol for TCP. */
#define IPPROTO_IP IPPROTO_IP
IPPROTO_ICMP = 1, /* Internet Control Message Protocol. */
#define IPPROTO_ICMP IPPROTO_ICMP
IPPROTO_IGMP = 2, /* Internet Group Management Protocol. */
#define IPPROTO_IGMP IPPROTO_IGMP
Here enum symbols are also exported as macros as required by the relevant POSIX spec, quoting:
The header shall define the following macros for use as
values of the level argument of getsockopt() and setsockopt():
IPPROTO_IP
Internet protocol.
IPPROTO_IPV6
Internet Protocol Version 6.
...
This pattern is also useful for feature-detection of registers in microprocessors, as in this question. For instance, there may be two similar header files, one of which defines one timer, and one that defines 2:
cheapprocessor.h:
#define TMR1 TMR1
extern volatile int TMR1;
expensiveprocessor.h:
#define TMR1 TMR1
extern volatile int TMR1;
#define TMR2 TMR2
extern volatile int TMR2;
Which means in your main code, when you include a generic processor.h that delegates to the appropriate header for the target, you can detect features:
#include <processor.h>
#ifdef TMR2
x = TMR2;
#else
x = 0; // no timer, probably because we're on the cheaper model
#endif