Place #define in structure - c

From linux kernel code
struct gpio_desc {
struct gpio_chip *chip;
unsigned long flags;
/* flag symbols are bit numbers */
#define FLAG_REQUESTED 0
#define FLAG_IS_OUT 1
#define FLAG_EXPORT 2 /* protected by sysfs_lock */
#define FLAG_SYSFS 3 /* exported via /sys/class/gpio/control */
#define FLAG_ACTIVE_LOW 6 /* value has active low */
#define FLAG_OPEN_DRAIN 7 /* Gpio is open drain type */
#define FLAG_OPEN_SOURCE 8 /* Gpio is open source type */
#define FLAG_USED_AS_IRQ 9 /* GPIO is connected to an IRQ */
#define FLAG_IS_HOGGED 11 /* GPIO is hogged */
/* Connection label */
const char *label;
/* Name of the GPIO */
const char *name;
};
what is the reason to place defines into the body of structure?

With #define it doesn't matter too much where you put them (so long as it is higher up in the file than where it is first used). Most likely those constants are used only within that structure, so it was put there so logically they would be easier to find. They could have been put anywhere above the first place they were used, but they were grouped together because of similar purpose.

It's meaningless, other than to try and define them close to the point of first use.
By the time the compiler actually sees the code, the preprocessor will have stripped those lines out of it.
In this particular example, they would be better off with a typedef'd enum for the flags and using that enum to declare the field.

There is no impact.
But in the example, for readability sake they maintained/added near to the variable declared.
They want use those "#define" for the variable "unsigned long flags;".
Below is simple example and proves no impact on the class/struct by declaring the "#Define" inside.
//gcc 4.9.3
#include <stdio.h>
struct gpio_desc {
#define FLAG_REQUESTED 0
} test;
int main()
{
printf("%d",FLAG_REQUESTED);
}
The out put is zero.

Related

Is there a way to directly access constants from a C header in a Swift program?

I've got a C-based program that includes a .h file full of domain-specific constants and enums; it looks something like this contrived example (just longer):
#ifndef MyProgramConstants_h
#define MyProgramConstants_h
#define MY_PROGRAM_NAME "MyProgram"
#define MY_PROGRAM_PROTOCOL_VERSION 1.2345
#define MY_PROGRAM_TCP_PORT 33666
enum {
SpecialConstantA = 0, /**< speed of light */
SpecialConstantB, /**< speed of sound */
SpecialConstantC, /**< speed of thought */
NumSpecialConstants /**< guard value */
};
#endif
Meanwhile, there is a Swift/iOS application (not written by me) that checks out the above codebase as a git-submodule, and links to parts of it via Objective-C bridging.
This all works fine, my only gripe is that the Swift application has its own separate .h file that redeclares all of the same constants as above, using Swift's Objective-C's slightly different syntax, e.g.:
#import <Foundation/Foundation.h>
#define PROGRAM_NAME "MyProgram"
#define PROGRAM_PROTOCOL_VERSION 1.2345
#define PROGRAM_PORT 33666
typedef NS_ENUM(uint32_t, SpecialConstants) {
SpecialConstantA = 0, /**< speed of light */
SpecialConstantB, /**< speed of sound */
SpecialConstantC, /**< speed of thought */
NumSpecialConstants /**< guard value */
};
That works too, but now the constants are declared in two different locations, and anyone who updates the value of a constant in the C header has to also remember to update the corresponding constant in the SwiftObjective-C header (and vice-versa), or else the constants will be inconsistent across languages and the behavior of the Swift program will be different from the behavior of the C code.
My question is, is there any way to get the Swift program to read this C header directly, as opposed to replicating it? It looks like the #define syntax is identical in both languages, so I could presumably move at least those out to a separate cross-language .h file and #import them from a .swift file and #include them from my C header, but the enums looks a bit more tricky.

Why can't I have an inner structure when two files include each other?

For context, I'm writing an operating system:
I have a struct vt_device_s and a struct __vt_device_s which is architecture specific and lives inside of vt_device_s like so:
struct
vt_device_s
{
struct __vt_device_s __device;
size_t cursor_x;
size_t cursor_y;
};
Now for the architectural struct:
struct
__vt_device_s
{
uint16_t *memory;
size_t memory_len;
};
The header <dev/vt.h> knows about __vt_device_s defined in <sys/_vt.h> because it is included, yet I get this error:
error: field '__device' has incomplete type
48 | struct __vt_device_s __device;
|
I realise this is because both files rely on each other (the whole conflict is caused by _vt.c including _vt.h including vt.h including _vt.h) but I don't understand how it is a compile problem. I have include guards in both files!
PS: I understand this would be a non-issue if I used a pointer but as it's an operating system, this driver needs to function before paging is set up (that is, malloc and free don't exist yet).
Here are the three files in question:
dev/vt.h
#ifndef _DEV_VT_H_
#define _DEV_VT_H_ 1
#include <stddef.h>
#include <sys/_vt.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct
vt_device_s
{
struct __vt_device_s __device;
size_t cursor_x;
size_t cursor_y;
};
void vt_init(struct vt_device_s *);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _DEV_VT_H_ */
sys/_vt.h
#ifndef _I386__VT_H_
#define _I386__VT_H_ 1
#include <stddef.h>
#include <stdint.h>
#include <dev/vt.h>
#define __VT_WIDTH 80
#define __VT_HEIGHT 25
#define __VT_MEMOFF 0xb8000
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct
__vt_device_s
{
uint16_t *memory;
size_t memory_len;
};
void __vt_init(struct vt_device_s *);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _I386__VT_H_ */
sys/_vt.c
#include <sys/_vt.h>
void
__vt_init(struct vt_device_s *device)
{
device->__device.memory = (uint16_t *) __VT_MEMOFF;
device->__device.memory_len = __VT_WIDTH * __VT_HEIGHT;
}
Your double include guards prevent the one file from including itself when it is re-included by the other. The only way to fix this is you have got to break the cycle. Decide which header is "higher" and will include the "lower" and don't try to include the higher one from the lower one. The lower one must be valid on its own.
The reason for this is that the pre-processor has to transform multiple files into one linear sequence of lines for the compiler. The compiler has to see one set of file contents before the other.
If you have cyclic includes like this you make it up to the final user of the code which one comes first. If they include file A, then it will include file B, which will try to include file A again but it will be prevented by the include guards, so the contents of B will be parsed first. On the other hand if the final user includes B first, then the contents of A will be seen first by the compiler.
So if you leave it like it is, then it is effectively random which file gets included first. If you break the cycle, you get to decide yourself which is included first.
Once you have decided, you can fix the compiler errors about incomplete types by making whichever file you choose to put first able to stand on its own and then letting the one that is second use definitions from the first.

In C, using multiple files, how to typedef and initialize a struct

For starters, I don't have a lot of experience using C. For a small sensor project I've been busy programming a PIC micro-controller however I've now run into the following "problem".
To make the code more readable I want to combine certain values from the PIC library into a couple of structures. To me a proper code structure would seem that I will typedef the structure I want and initialize it in a separate file from the main program and then import this into the main file. This would prevent the main code file from being cluttered with these initializations which I think is desirable.
Some pseudo code to clarify. pin_A and RESULT_A are from the PIC library:
sensor.h
// Define the structures for the individual sensor pads and the sensors.
typedef struct{
int pin;
unsigned int result;
}PAD;
typedef struct{
PAD A;
PAD B;
}SENSOR;
sensor.c
(I use sensor.c as an example here because I assume that is where the initialization should happen, but please correct me if I'm wrong.)
#include "sensor.h"
PAD PAD_A = {.pin=pin_A, .result=RESULT_A};
PAD PAD_B = {.pin=pin_B, .result=RESULT_B};
SENSOR sens = {.A=PAD_A, .B=PAD_B}
main.c
#include ... something
void main(){
// call a constructor or something
while(1){
printf(sens.A.pin); // I don't really want to print however this is an example of course.
};
To me something like this should be very common in coding however I've been unable to find helpful information on how to approach this. I assume I'm missing something obvious so please point it out.
My current workaround is to include the sensor.h file in main.c and do all the initialization there. However this makes for very cluttered and non portable code to I can't imagine that is how it should be done.
Regards,
----------------------------- Edit ------------------------------------
Because the question appears to be unclear I will try and add to it. The core of my confusion was that I was unable to define, and initialize e.t.c., certain variables when using multiple files. One method I imagine will work (though not it's not popular among many) is the use of global variables. My problem was that nearly all examples that I could find that do this provide code only in a single file and don't use header files that I believe are required to provide structure to a larger project.
For future references, in the end I have settled on the use of a constructor function as opposed to global variables. This was based on the post referenced by jonathan leffler in the comments below. I'll add the code I'm currently using pertaining to this question as an example to others. Though it is likely not the most optimized and will contain some style errors it is functional.
padDefinitions.h
/* As provided by microchip but renamed for convenience */
#define PIN_A 17
#define PIN_B 12
#define PIN_C 18
#define PIN_D 16
#define PIN_E 15
#define PIN_F 13
#define PIN_G 5
#define PIN_H 1
#define PIN_I 0
#define PIN_J 11
#define PIN_K 10
#define PIN_L 9
#define PIN_GUARD 14
#define RESULT_A &ADC1BUF17
#define RESULT_B &ADC1BUF12
#define RESULT_C &ADC1BUF18
#define RESULT_D &ADC1BUF16
#define RESULT_E &ADC1BUF15
#define RESULT_F &ADC1BUF13
#define RESULT_G &ADC1BUF5
#define RESULT_H &ADC1BUF1
#define RESULT_I &ADC1BUF0
#define RESULT_J &ADC1BUF11
#define RESULT_K &ADC1BUF10
#define RESULT_L &ADC1BUF9
#define RESULT_GUARD &ADC1BUF14
sensordef.h
/* Defines structures for the sensor pads and the sensor (which is a combination of pads) */
typedef struct PAD{
int pin; // The pin on the device the pad is connected to
volatile unsigned int current_value; // The current value of the pad
unsigned int calculated_value; // Storage for calculated (iir) value
}PAD;
typedef struct SENSOR{
PAD A;
PAD B;
PAD C;
PAD D;
PAD E;
PAD F;
PAD G;
PAD H;
PAD I;
PAD J;
PAD K;
PAD L;
}SENSOR;
/* Declare the constructor functions */
PAD PadConstructor();
SENSOR SensorConstructor();
sensordef.c
#include "sensordef.h"
#include "padDefinitions.h"
SENSOR SensorConstructor(){
/* Initialize the pads and sensor variables */
// Define all the pads
PAD PAD_A = {.pin=PIN_A, .current_value=*RESULT_A};
PAD PAD_B = {.pin=PIN_B, .current_value=*RESULT_B};
PAD PAD_C = {.pin=PIN_C, .current_value=*RESULT_C};
PAD PAD_D = {.pin=PIN_D, .current_value=*RESULT_D};
PAD PAD_E = {.pin=PIN_E, .current_value=*RESULT_E};
PAD PAD_F = {.pin=PIN_F, .current_value=*RESULT_F};
PAD PAD_G = {.pin=PIN_G, .current_value=*RESULT_G};
PAD PAD_H = {.pin=PIN_H, .current_value=*RESULT_H};
PAD PAD_I = {.pin=PIN_I, .current_value=*RESULT_I};
PAD PAD_J = {.pin=PIN_J, .current_value=*RESULT_J};
PAD PAD_K = {.pin=PIN_K, .current_value=*RESULT_K};
PAD PAD_L = {.pin=PIN_L, .current_value=*RESULT_L};
// Define a variable for the sensor
SENSOR sensor = {
.A=PAD_A, .B=PAD_B, .C=PAD_C,
.D=PAD_D, .E=PAD_E, .F=PAD_F,
.G=PAD_G, .H=PAD_H, .I=PAD_I,
.J=PAD_J, .K=PAD_K, .L=PAD_L,
};
return sensor;
}
main.c
int16_t main(void){
#include "sensordef.h"
/* ... Initialization code for the PIC ... */
SENSOR sensor;
sensor = SensorConstructor();
while(1)
{
/* ... Perform measurements ... */
}
}
You can write an extern variable declaration into your sensor.h file:
sensor.h
…other definitions…
typedef struct{
PAD A;
PAD B;
} SENSOR;
extern SENSOR sens;
main.c
#include "sensor.h"
Now the compiler knows that there is a global variable sens with type SENSOR.
As jonathan leffler pointed out in the comments. How do I use extern to share variables between source files in C? provides ample information on regarding my question. It provides a clear, and very lengthy, example of how to use multiple files for declaration and definition of variables.
Thank you Jonathan. (+1 from me if I had the reputation to do so)

Trying to understand macros that define file types

So i've been trying to debug a program in gdb and for me to understand a certain part I needed to analyze it.
if (!S_ISREG(st->st_mode))
if (!(st->st_mode & S_IXUSR))
In the if's above, the S_ISREG and S_IXUSR are the macros that I don't understand. As I tried to investigate more into these macros I found these other macros:
/* File types. */
#define __S_IFDIR 0040000 /* Directory. */
#define __S_IFCHR 0020000 /* Character device. */
#define __S_IFBLK 0060000 /* Block device. */
#define __S_IFREG 0100000 /* Regular file. */
#define __S_IFIFO 0010000 /* FIFO. */
#define __S_IFLNK 0120000 /* Symbolic link. */`enter code here`
#define __S_IFSOCK 0140000 /* Socket. */
All i want to know is what the numbers next to the macros mean? And what about these macros starting with "__" I think I heard a while back that these were child macros or something. If someone can explain both of these it would be awesome!
You see, whoever created this file system just need some different value to represent different type of file,and one value to one type,there is not specific reason why 0040000 represents directory, if you are the author of the file system,you can specify any value you like to represent directory,so there is no why , just follow the comment and know it.

Can a preprocessor function be used to define multiple preprocessor macros?

Is it possible to create a preprocessor function that will cause multiple other preoprocessor macros to be defined?
I'm working in a micro controller framework that requires a few macros to be made in order for a generic interrupt handler to function:
<MODULE_NAME>_IRQ_PIN //ex: PORTB_PIN(0)
<MODULE_NAME>_IRQ_IN_REGISTER //ex: GPIO_PBIN
<MODULE_NAME>_IRQ_NUMBER //ex: GPIO_IRQA
<MODULE_NAME>_IRQ_INTCFG_REG //ex: GPIO_INTCFGA
I am trying to make this process more generic and easier from an implementation standpoint. There are about ten of these macros that need to be defined, but their definitions can all be derived when given 1) the port name 2) the pin number and 3) the IRQ name. I am hoping then to create a pre-processor function that will result in the generation of all of these macros. Something like:
#define MAKE_INTERRUPT_MACROS(module, port, pin, irq_num) \
#define module##_IRQ_pin PORT##port##_PIN(##pin##) \
#define module##_IRQ_IN_REGISTER GPIO_P##port##IN \
#define module##_IRQ_NUMBER GPIO_IRQ##irq_num \
#define module##_IRQ_INTCFG_REG GPIO_INTCFG##irq_num
Is there a legal way to get the proprocessor to do something like the above, where a single preprocessor function causes the generation of multiple other macros based on the parameters passed to the function?
I think this classical scheme may solve your problem. This is a simple and clear way:
#ifdef CPU_X
#define IRQ_PIN 0
#define IRQ_IN_REGISTER 3
#define IRQ_NUMBER 11
#define IRQ_INTCFG_REG 12
#endif
#ifdef CPU_YY
#define IRQ_PIN PORTB_PIN(1)
#define IRQ_IN_REGISTER GPIO_PBIN(6)
#define IRQ_NUMBER GPIO_IRQA(9)
#define IRQ_INTCFG_REG GPIO_INTCFGA(0xA)
#endif
#ifdef CPU_KK
/* .
. Another CPU
.
*/
#endif
#ifdef CPU_K2
/* .
. Another CPU
.
*/
#endif
You may compile the code specifying the CPU using -D CPU_xx and the problem shoudl be solved!
I assume you might have some other macros (E.G.: GPIO_IRQA(9)), and in CPU_YY I've used it, but It might be used also for the other CPUs.
If you can use C++ rather than C, look at using classes, one per CPU type, and simply use constants and interfaces in the class. Then, you don't even care that they are different, simply use the same names to access them (the differentiation is done based upon the class being instantiated.
If you really and truly must use C (such as writing a device driver), you can use the approach device driver writers use (all flavors of *nix, VxWorks, PSOS, QNX, and most of the old DEC OSs use this approach, don't know about Windows): Simply build a structure containing the values and any functions you may need to manipulate the hardware (or anything else, for that matter). Create one instance of this structure per hardware (or in your case, module) type. Then indirect through the structure.
Example:
struct module_wrapper {
const char *module_name;
int irq_pin;
int irq_register;
int irq_number;
int irq_intcfg_reg;
int (*init_fcn)(void);
int (*reg_access)(int register_number);
int (*open)(void);
int (*close)(void);
int (*read)(char *dst_buffer, int len);
int (*write)(const char *src_buffer, int len);
};
module_wrapper portB = { /* initialize here */ };
module_wrapper gpio = { /* initialize here */ };
printf("GPIO pin %d\n", gpio.irq_pin);
Obviously, modify as desired. You can also replace the constant variables with functions that return the values.
You can't define other macros with a macro, but you achieve something similar by doing it kind of in a totally opposite way.
You could autogenerate a file which has the following block for each possible module:
#ifdef <MODULE>_IRQ_DATA
#define <MODULE>_IRQ_pin CALL(GET_IRQ_PIN, <MODULE>_IRQ_DATA)
#define <MODULE>_IRQ_IN_REGISTER CALL(GET_IRQ_IN_REGISTER, <MODULE>_IRQ_DATA)
#define <MODULE>_IRQ_NUMBER CALL(GET_IRQ_NUMBER, <MODULE>_IRQ_DATA)
#define <MODULE>_IRQ_INTCFG_REG CALL(GET_IRQ_INTCFG_REG, <MODULE>_IRQ_DATA)
#endif
And then have:
#define CALL(MACRO, ...) MACRO(__VA_ARGS__)
#define GET_IRQ_PIN(port, pin, irq_num) PORT##port##_PIN(pin)
#define GET_IRQ_IN_REGISTER(port, pin, irq_num) GPIO_P##port##IN
#define GET_IRQ_NUMBER(port, pin, irq_num) GPIO_IRQ##irq_num
#define GET_IRQ_INTCFG_REG(port, pin, irq_num) GPIO_INTCFG##irq_num
(Depending on how the defines are used, you can possibly get rid of the #ifdef-#endif -pairs, eg. if all of them must/can always be defined)
Then actually defining the needed values could be done with just:
#define <MODULE>_IRQ_DATA B,0,A

Resources