c program functionality confusion - c

I'm pretty new to c programming and I have this following program to degub. Problem is, I have no idea what these lines of code even mean. Could anyone point me in the direction of what they mean as far as from a syntax point of view/functionality? What does the code do? The code is compiled with MPLab C30 v3.23 or higher.
fractional abcCoefficient[3] __attribute__ ((space(xmemory))); /*ABC Coefficients loaded from X memory*/
fractional controlHistory[3] __attribute__ ((space(ymemory))); /*Control History loaded from Y memory*/
fractional kCoeffs[] = {0,0,0}; /*Kp,Ki,and Kd gains array initialized to zero*/

These lines declare variables; there's no execution code associated with what you've pasted.
The environment this code is intended for understands that fractional is a type; either in the same file or in a header this file includes (directly or indirectly), fractional will be defined with a typedef statement. In your examples, each of the variables are arrays of three fractional types.
The __attribute__ ((space(?memory))) entries are attributes the compiler intended to build this understands and affect something regarding how the variables are managed. You'll want to consult the compiler documentation for the platform you're using.

See this page to learn about __attribute__ in gcc (however, I don't see a space(xmemory) option in there, consult your compiler's documentation if it's not gcc. If it is, then space() can be a macro).
fractional is also a custom type, search for typedef definitions for fractional.
Basically, the code is creating a bunch of arrays of type fractional. The first two make use of gcc's attribute extension (or whatever compiler you are using), and the last one is initialized to 0 on every position.

The first two lines declare arrays with three elements each. The type is fractional, which is probably a typedef (to a struct with numerator and denominator?).
The comments suggest that the data is stored in another memory space, perhaps some sort of Flash.
So the program seems to be for an embedded system.

It looks like "fractional" is a custom type, look for its typedef somewhere and it should get you started on what you're looking at. I expect these are variable declarations.
Macros are established using the "#define" preprocessor directive, so you can look for "#define space(x) code" somewhere to tell you what it does. Good luck.

Related

lldb in xcode detects integer called I to be a complex number

I have a C code, within which an int I gets declared and initialized. When I'm debugging within xcode, if I try to print the value of I, xcode tries to find a complex number:
(lldb) p I
error: <lldb wrapper prefix>:43:31: expected unqualified-id
using $__lldb_local_vars::I;
^
<user expression 3>:1760:11: expanded from here
#define I _Complex_I
^
<user expression 3>:7162:20: expanded from here
#define _Complex_I ( __extension__ 1.0iF )
When I try the same thing (stopping at the same exact line in the code) in the command line, without using xcode, it works fine:
(lldb) p I
(int) $0 = 56
I'm loading the following libraries:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
which shouldn't even include complex numbers, no? I definitely don't have a macro that defines I to be the complex variable. The one I run in xcode, I compile with the default xcode tools. The one I run in the command line, I use gcc. Is this the difference, somehow? Is xcode including more libraries than I ask it to? Why is this happening and how can I prevent it?
Edit: I should also add that the variable explorer in xcode shows the value of I correctly, as an integer.
$__lldb_local_vars is an artificial namespace that lldb injects into the wrapper it sets up for your expression before compilation so that clang can find the frame's local variables and their types. The problem comes as others have noted because we also run the preprocessor when compiling your expression, and your variable name collides with a preprocessor symbol in the expression context.
Normally, debug information does not record macros at all, so you aren't seeing the complex.h version of I from your own use of it in your code. Rather, you are seeing the I macro because something has caused the Darwin module to be imported into lldb's expression context.
That can happen in two ways, either because you explicitly asked for it by running:
(lldb) expr #import Darwin
or because you built this program with -fmodules and your code imported the Darwin module by inserting a statement like the above.
Doing this by hand is a common trick explicitly to make #defines from the module visible to the expression parser. Since it is the visibility of the macro that is causing problems, then you will have to stop doing that if you want this expression to succeed.
OTOH, if lldb is doing this because the debug information recorded that some part of you code imported this module, you can turn off the behavior by putting:
settings set target.auto-import-clang-modules 0
in your ~/.lldbinit and restarting your debug session.
BTW, the p command (or the expression command that p is an alias for) evaluates the text you provide it as a regular expression using the language and in the context of the current frame, with as much access to symbols, defines and the like as lldb can provide. Most users also want to be able to access class information that might not be directly visible in the current frame, so it tends to cast as wide a net as possible looking for symbols and types in order to enable this.
It is a very powerful feature, but as you are seeing sometimes the desire to provide this wide access for expressions can cause conflicting definitions. And anyway, it is way more powerful than needed just to view a local variable.
lldb has another command: frame var (convenient alias v) that prints local variable values by directly accessing the memory pointed to by the debug information and presenting it using the type from the debug info. It supports a limited subset of C-like syntax for subelement reference; you can use * to dereference, . or -> and if the variable is an array [0] etc...
So unless you really do need to run an expression (for instance to access a computed property or call another function), v will be faster and because its implementation is simpler and more direct, it will have less chance of subtle failures than p.
If you also want to access the object definition of some ObjC or Swift local variable, the command vo or frame var -O will fetch the description of the local variable it finds using the v method.
I definitely don't have a macro that defines I to be the complex variable.
It looks like lldb is getting confused somehow, not an issue with your code, but without a MRE it is hard to say.
The one I run in xcode, I compile with the default xcode tools. The one I run in the command line, I use gcc. Is this the difference, somehow?
xcode uses "Apple clang" (an old, custom version) with libc++ by default, as far as I know. gcc is quite different and it may not even use libc++.
Having said that, since xcode shows the variable as an integer but lldb does not, it looks like something else is going on.
Is xcode including more libraries than I ask it to?
I don't think so given the program works and Xcode shows the value as an integer.
Why is this happening and how can I prevent it?
Hard to say since it is a closed source tool. Try to make an MRE. It usually helps debugging the issue and finding workarounds.
By definition a complex number is not defined as simply int
Additionally, as mentioned, complex I is defined in <complex.h>:
To construct complex numbers you need a way to indicate the imaginary
part of a number. There is no standard notation for an imaginary
floating point constant. Instead, complex.h defines two macros that
can be used to create complex numbers.
Macro: const float complex _Complex_I
This macro is a representation of the complex number “0+1i”. Multiplying a real floating-point value by _Complex_I gives a complex number whose value is purely imaginary. You can use this to construct complex constants:
3.0 + 4.0i = 3.0 + 4.0 * _Complex_I
Note that _Complex_I * _Complex_I has the value -1, but the type of that value is complex.
_Complex_I is a bit of a mouthful. complex.h also defines a shorter name for the same constant.
Macro: const float complex I
This macro has exactly the same value as _Complex_I. Most of the time it is preferable. However, it causes problems if you want to use the identifier I for something else. You can safely write
#include <complex.h>
#undef I
Reference here for GNU implementation
Include this header file (or similar from your environment), and no need to define it yourself

initialising constant static array with algorhythm [duplicate]

I am thinking about the following problem: I want to program a microcontroller (let's say an AVR mega type) with a program that uses some sort of look-up tables.
The first attempt would be to locate the table in a separate file and create it using any other scripting language/program/.... In this case there is quite some effort in creating the necessary source files for C.
My thought was now to use the preprocessor and compiler to handle things. I tried to implement this with a table of sine values (just as an example):
#include <avr/io.h>
#include <math.h>
#define S1(i,n) ((uint8_t) sin(M_PI*(i)/n*255))
#define S4(i,n) S1(i,n), S1(i+1,n), S1(i+2,n), S1(i+3,n)
uint8_t lut[] = {S4(0,4)};
void main()
{
uint8_t val, i;
for(i=0; i<4; i++)
{
val = lut[i];
}
}
If I compile this code I get warnings about the sin function. Further in the assembly there is nothing in the section .data. If I just remove the sin in the third line I get the data in the assembly. Clearly all information are available at compile time.
Can you tell me if there is a way to achieve what I intent: The compiler calculates as many values as offline possible? Or is the best way to go using an external script/program/... to calculate the table entries and add these to a separate file that will just be #included?
The general problem here is that sin call makes this initialization de facto illegal, according to rules of C language, as it's not constant expression per se and you're initializing array of static storage duration, which requires that. This also explains why your array is not in .data section.
C11 (N1570) §6.6/2,3 Constant expressions (emphasis mine)
A constant expression can be evaluated during translation rather than
runtime, and accordingly may be used in any place that a constant may
be.
Constant expressions shall not contain assignment, increment,
decrement, function-call, or comma operators, except when they are
contained within a subexpression that is not evaluated.115)
However as by #ShafikYaghmour's comment GCC will replace sin function call with its built-in counterpart (unless -fno-builtin option is present), that is likely to be treated as constant expression. According to 6.57 Other Built-in Functions Provided by GCC:
GCC includes built-in versions of many of the functions in the
standard C library. The versions prefixed with __builtin_ are always
treated as having the same meaning as the C library function even if
you specify the -fno-builtin option.
What you are trying is not part of the C language. In situations like this, I have written code following this pattern:
#if GENERATE_SOURCECODE
int main (void)
{
... Code that uses printf to write C code to stdout
}
#else
// Source code generated by the code above
... Here I paste in what the code above generated
// The rest of the program
#endif
Every time you need to change it, you run the code with GENERATE_SOURCECODE defined, and paste in the output. Works well if your code is self contained and the generated output only ever changes if the code generating it changes.
First of all, it should go without saying that you should evaluate (probably by experiment) whether this is worth doing. Your lookup table is going to increase your data size and programmer effort, but may or may not provide a runtime speed increase that you need.
If you still want to do it, I don't think the C preprocessor can do it straightforwardly, because it has no facilities for iteration or recursion.
The most robust way to go about this would be to write a program in C or some other language to print out C source for the table, and then include that file in your program using the preprocessor. If you are using a tool like make, you can create a rule to generate the table file and have your .c file depend on that file.
On the other hand, if you are sure you are never going to change this table, you could write a program to generate it once and just paste it in.

How do most embedded C compilers define symbols for memory mapped I/O?

I often times write to memory mapped I/O pins like this
P3OUT |= BIT1;
I assumed that P3OUT was being replaced with something like this by my preprocessor:
*((unsigned short *) 0x0222u)
But I dug into an H file today and saw something along these lines:
volatile unsigned short P3OUT # 0x0222u;
There's some more expansion going on before that, but it is generally that. A symbol '#' is being used. Above that there are some #pragma's about using an extended set of the C language. I am assuming this is some sort of directive to the linker and effectively a symbol is being defined as being at that location in the memory map.
Was my assumption right for what happens most of the time on most compilers? Does it matter one way or the other? Where did that # notation come from, is it some sort of standard?
I am using IAR Embedded workbench.
This question is similar to this one: How to place a variable at a given absolute address in memory (with GCC).
It matches what I assumed my compiler was doing anyway.
Although an expression like (unsigned char *)0x1234 will, on many compilers, yield a pointer to hardware address 0x1234, nothing in the standard requires any particular relationship between an integer which is cast to a pointer and the resulting address. The only thing which the standard specifies is that if a particular integer type is at least as large as intptr_t, and casting a pointer to that particular type yields some value, then casting that particular value back to the original pointer type will yield a pointer equivalent to the original.
The IAR compiler offers a non-standard extension which allows the compiler to request that variables be placed at specified hard-coded addresses. This offers some advantages compared to using macros to create pointer expressions. For one thing, it ensures that such variables will be regarded syntactically as variables; while pointer-kludge expressions will generally be interpreted correctly when used in legitimate code, it's possible for illegitimate code which should fail with a compile-time error to compile but produce something other than the desired effect. Further, the IAR syntax defines symbols which are available to the linker and may thus be used within assembly-language modules. By contrast, a .H file which defines pointer-kludge macros will not be usable within an assembly-language module; any hardware which will be used in both C and assembly code will need to have its address specified in two separate places.
The short answer to the question in your title is "differently". What's worse is that compilers from different vendors for the same target processor will use different approaches. This one
volatile unsigned short P3OUT # 0x0222u;
Is a common way to place a variable at a fixed address. But you will also see it used to identify individual bits within a memory mapped location = especially for microcontrollers which have bit-wide instructions like the PIC families.
These are things that the C Standard does not address, and should IMHO, as small embedded microcontrollers will eventually end up being the main market for C (yes, I know the kernel is written in C, but a lot of user-space stuff is moving to C++).
I actually joined the C committee to try and drive for changes in this area, but my sponsorship went away and it's a very expensive hobby.
A similar area is declaring a function to be an ISR.
This document shows one of the approaches we considered

An Example of complicated define in C

#define _FUID1(x) __attribute__((section("__FUID1.sec"),space(prog))) int _FUID1 = (x);
I am trying to make sense of the about the above define. the _FUID(x) macro. This relates to program memory and has the attribute of the section defining in the code section memory area?
what does the above trying to accomplish?
The macro isn't doing anything interesting or complicated at all; it just outputs a declaration for int _FUID1, with its parameter as an initializer, and with an attributes list ahead of it.
As for what the attributes list means, look at the documentation for variable attributes in GCC. section puts the variable in a named section, which allows the linker to relocate it to a special address or do some other interesting thing to it, and space isn't documented, but space(prog) sounds like a directive to put a value into the program address space instead of the data address space on a Harvard-architecture machine.
I think this is hardware specific (some Microchip unit), it places a value, for example:
__attribute__((section("__FUID1.sec"),space(prog))) int _FUID1 = (0xf1);
into unit id register 1 (__FUID1.sec), in the program flash to configure the hardware. See the pic documentation (for references to FUID) and MPLAB C30 manual (for description of memory spaces).

Finding the elements in a structure in C language

Is it possible to determine the elements(name & datatype) in a structure(C language) in a library ? If yes, how to do it in C language ? If C language does not support it, Is it possible to get the structure elements by other tricks or is there any tool for it?
Do you mean find out when you are programming, or dynamically at runtime?
For the former, sure. Just find the .h file which you are including and you will find the struct definition there including all the fields.
For the latter, no, it is not possible. C compiles structs to machine code in such a way that all of this information is lost. For example, if you have a struct {int x, float y, int z}, and you have some code which says
a = mystruct.y
in the machine code, all that will remain is something like finding the pointer to mystruct, adding 4 to it (the size of the int), and reading 4 bytes from there, then doing some floating point operations to it. Neither the names nor the types of those struct fields will be accessible at all, and therefore, there is no way to find them out at runtime.
No, it isn't possible. C has no inbuilt reflection-style support.
If by "determine the elements of a structure" you mean "get the declaration of that structure type programmatically", then I do not believe that it is possible - at least not portably. Contrary to more modern languages like C++ ot Java, C does not keep type information in a form available to the actual program.
EDIT:
To clarify my comment about it being impossible "portably":
There could very well be some compiler+debugging format combination that would embed the necessary information in the object files that it produces, although I can't say I know of one. You could then, hypothetically, have the program open its own executable file and parse the debugging information. But this is a cumbersome and fragile approach, at best...
Why do you need to do something like that?

Resources