What's the meaning of F(string) in C++? - c++

Currently I'm writing C++ code on Arduino. In an example, I find a expression
Serial.print(F("Disconnected from central:"));
It's obvious that this statement is used to send string to the serial, but why it uses F(string) instead of using string directly?
I try to google it but with no results. If someone know it, I would be greatly appreciated.

This macro is Arduino-specific, it's not "C++" as such.
It places the string in flash memory, to conserve RAM.
It means the string cannot be modified when the program runs.
One current definition is:
#define F(slit) (reinterpret_cast<const __FlashStringHelper *>(PSTR(slit)))
See the source code for more.

F() is one of the most powerful functions, which was added with the 1.0 release of the IDE. I keep mixing the terms macro and function. F() really isn’t a function, it is a #define macro which lives in WString.h
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))
It is a macro, which use for storing strings in flash memory rather than RAM.

Related

Using #define for printf, does it effect on speed

I am using
#define printInt(x) printf ("%d",x)
In main()
I can use it like this:
int var=10;
printInt (var);
Which is easier to use than typing
printf ("%d",var);
Will using my own #define for printing an int, float etc make my program slower?
No this will not effect the speed. The macro is expanded during pre-processing so that in every instance that you use printInt(myInt) what is actually passed to the compiler will be printf("%d", myInt). So I think the binary output would be identical either way.
No, it doesn't affect the speed of your program.
The #define instructions are processed by the preprocessor before your program is compiled.
For example the call
printInt(var);
is replaced with
printf ("%d",var);
by the preprocessor.
Therefore the compiler can't determine if a #define was used or not. In both cases it leads to the same code (and the same program). Thats the reason why it isn't possible that both programs differ in their speed.
EDIT: If you use a lot of #defines in your program, it is possible that the speed of the proprocessing step decreases. But in most cases this should be no problem.

Arduino - How to write Macro that define used pins by name and number and throw compiler error if pin is used elsewhere

I have been playing with this for the last 2 hours now. It should be simple but it does not work. I am not really familiar with macros and I never used them really because of their known instability. But in this case... I don't see any other better way to not use any chip memory.
What I want is not to use memory on chip for this so I choose precompiler directives, especially macros. The macro just have to define stuff, not return anything. I want that macro to be equivalent to this code :
#define PIN3 = 13;
#define PINLED = 13;
And it should be called like that :
P(13,LED);
So that way I can reference PINLED in my code and get a compiler error if any other library or code I use happens to use PIN13 when I put the P(13,LED) in the top of all the files that uses this pin in my project. I want something that names all pins the same way.
I want the 2 constants/defines to be "defined" so PIN13 cause a compiler error, but PINLED might be named different in many projects
I have tried this :
#define P(no_,name_) \
if (true) { \
PIN##name_ = no_; \
PIN##no_ = no_; \
}\
else true
This works but does only 1 define instead of 2 :
#define P(no_,name_) PIN##name_ = no_
This was suggested by many as the correct syntax. I also tried with the do... while(0) syntax and other tricks so I can use the macro as a function with a ; after it but is does not work and always throws some error.
I am using the Ino project to build because I cannot live with the arduino IDE which is pure crap compared to other IDEs.
Sorry, but your question is hardly understandable. You say you want to check whether a pin has already been used in another part of the project, and in the same time you're showing code for defining macros in macros.
But that's where it hurts, like #graben showed, it's simply not possible to achieve in C. First of all both of your syntaxes are wrong:
#define P(no_,name_) PIN##name_ = no_
you're not creating a macro name PINLED to which you assign 13, but you're assigning to the C variable PINLED the value 13. To make your PIN definition macro work, you'll need to use const int variables, which usually are easily optimized by the compiler.
Now, to get to the goal you say you want to achieve, I think it's very unlikely you can do it in macro processor code, at least in an elegant way...
And I don't think that's even necessary!
If you design well your libraries, you should not be using the pin number throughout your code and libraries, but design them so you define pins for each library at the library initialization stage. That's why usually Arduino libraries work in three steps:
allocate the memory (which is done by calling the constructor, which is often made in the included header file as a global object) ;
configure the instance (which is done with the .begin() method)
use the instance
so basically, if you have all your pins defined in the same file, you should not run into pin reuse elsewhere in your code.

Where does #define or char* strings reside in memory? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is a string literal in c++ created in static memory?
If I do:
const char* StringPtr = "string0",
then it is definitely somewhere in the memory, and I can get the address of StringPtr.
But if I do:
#define STRING0 "string0", then where does STRING0 reside?
Or, is STRING0 not existing in memory because compiler replace using of STRING0 by "string0"?
As far as I've known, whenever you write any string in your code, compiler must put it somewhere in the memory, but I don't know the exact behavior of it.
But I am not very sure about this.
Can anyone explain how strings that are #define-ed or declared as char* are manipulated by the compiler?
Also, which one is better? To #define, extern const char* or extern const std::stringin the header file for strings?
Thanks!
In almost all cases, the compiler is allowed to put a string literal wherever it wants. There might be one copy for each time the literal appears in source code, or one master copy shared among the instances.
This causes trouble sometimes in C where const doesn't mean the same thing and you are allowed to modify the memory. On one platform all the identical strings get changed, while on another changes don't propagate. As of C++11 string literals don't implicitly lose constness and the mistake is harder to make.
The strings will all be initialized before the program starts, so in effect they are part of the executable binary image. That much is certain.
What would be different is this:
const char StringPtr[] = "string0",
This defines a dedicated array object with a unique address.
stringPtr resides in the executable's data section. If you open your exe in a text editor you will be able to search for it.
Data Segment
The macro exists only for the duration of the preprocessing stage of building your program.
Depending on your compiler, if you use the macro method you can end up with several separate instances of an identical string in your exe, but if you use the char* method you can use just a single instance.
#define STRING0
STRING0 does NOT reside in memory. It does NOT even exist during compilation. In PRE-compilation all occurances of STRING0 are replaced with "string0" by the preprocessor. After this stage, none of the following stages or the compiled applications know of the existance of any symbol of the name STRING0
Once this happens, many of not all instances will end up as unique string literals(your const char* case) all over your code. The answer to where these are stored in memory is better answered by #Potatoswatter and the link provided by #silico
#define is a preprocessor macro. It will replace STRING0 with "string0" during the precompile stage before the code is then compiled.
"string0" resides in the executable's static read-only memory.
StringPtr is a variable, that is why you can take its address. It simply points at the memory address of "string0".
When you do the #define, there is not the compiler, but the preprocessor who replaces, textually, STRING0 with "string0" in the pre-processed source file, before passing it to the compiler proper.
The compiler never sees the STRING0, but only sees "string0" everywhere that you wrote STRING0.
edit:
Each instance of "string0" that replaces the STRING0 that you wrote in the source file is a string literals per se. If those string literals are guaranteed (or declared) as invariant, then the compiler might optimize memory allocation by storing a single copy of this "string0" and point other uses towards that copy (I rephrased this paragraph in edit).
(edit: those identical literal string constants might be merged into a singled copy, however this is is up to the compiler. THe standard does not require or enforce it: http://www.velocityreviews.com/forums/t946521-merging-of-string-literals-guaranteed-by-c-std.html )
As for your last question: the most portable is to declare those as: const char *
later edit: the best discussion about the string literals that I found so far is here: https://stackoverflow.com/a/2245983/1284631
Also, beware that a string literal can also appear in the initialization of statically-allocated char array, when it cannot be merged with other copies of it, since the content of the static array may be overwritten. See the example below, where the two identical string literals "hello" cannot be merged:
#include <stdio.h>
#include <string.h>
int main(){
char x[50]="hello";
printf("x=%s, &x[0]=%p\n",x,&x[0]);
const char *y="hello";
printf("y=%s, &y[0]=%p\n",y,&y[0]);
strcpy(&x[0],"zz");
printf("x=%s, &x[0]=%p\n",x,&x[0]);
return 0;
}
The output of this code is:
x=hello, &x[0]=0x7fff8a964370
y=hello, &y[0]=0x400714
x=zz, &x[0]=0x7fff8a964370

C and C++ Code Interoperability - Data Passing Issues

The following is the situation. There is a system/software which is completely written in C. This C program spawns a new thread to start some kind of a data processing engine written in C++. Hence, the system which I have, runs 2 threads (the main thread and the data processing engine thread). Now, I have written some function in C which takes in a C struct and passes it to the data processing thread so that a C++ function can access the C struct. While doing so, I am observing that the values of certain fields (like unsigned int) in the C struct changes when being accessed in the C++ side and I am not sure why. At the same time, if I pass around a primitive data type like an int, the value does not change. It would be great if someone can explain me why it behaves like this. The following is the code that i wrote.
`
/* C++ Function */
void DataProcessor::HandleDataRecv(custom_struct* cs)
{
/*Accesses the fields in the structure cs - an unsigned int field. The value of
field here is different from the value when accessed through the C function below.
*/
}
/*C Function */
void forwardData(custom_struct* cs)
{
dataProcessor->HandleDataRecv(cs); //Here dataProcessor is a reference to the object
//of the C++ class.
}
`
Also, both these functions are in different source files(one with .c ext and other with .cc ext)
I'd check that both sides layout the struct in the same
print sizeof(custom_struct) in both languages
Create an instance of custom_struct in both languages and print the offset of
each member variable.
My wild guess would be Michael Andresson is right, structure aligment might be the issue.
Try to compile both c and c++ files with
-fpack-struct=4
(or some other number for 4). This way, the struct is aligned the same in every case.
If we could see the struct declaration, it would probably clearer. The struct does not contain any #ifdef with c++-specific code like a constructor, does it? Also, check for #pragma pack directives which manipulate data alignment.
Maybe on one side the struct has 'empty bytes' added to make the variables align on 32 bit boundaries for speed (so a CPU register can point to the variable directly).
And on the other side the struct may be packed to conserve space.
(CORRECTION) With minor exceptions, C++ is a superset of C (meaning C89), So i'm confused about what is going on. I can only assume it has something to do with how you are passing or typing your variables, and/or the systems they are running on. It should, technically speaking, unless I am very mistaken, have nothing to do with c/c++ interoperability.
Some more details would help.

Does an arbitrary instruction pointer reside in a specific function?

I have a very difficult problem I'm trying to solve: Let's say I have an arbitrary instruction pointer. I need to find out if that instruction pointer resides in a specific function (let's call it "Foo").
One approach to this would be to try to find the start and ending bounds of the function and see if the IP resides in it. The starting bound is easy to find:
void *start = &Foo;
The problem is, I don't know how to get the ending address of the function (or how "long" the function is, in bytes of assembly).
Does anyone have any ideas how you would get the "length" of a function, or a completely different way of doing this?
Let's assume that there is no SEH or C++ exception handling in the function. Also note that I am on a win32 platform, and have full access to the win32 api.
This won't work. You're presuming functions are contigous in memory and that one address will map to one function. The optimizer has a lot of leeway here and can move code from functions around the image.
If you have PDB files, you can use something like the dbghelp or DIA API's to figure this out. For instance, SymFromAddr. There may be some ambiguity here as a single address can map to multiple functions.
I've seen code that tries to do this before with something like:
#pragma optimize("", off)
void Foo()
{
}
void FooEnd()
{
}
#pragma optimize("", on)
And then FooEnd-Foo was used to compute the length of function Foo. This approach is incredibly error prone and still makes a lot of assumptions about exactly how the code is generated.
Look at the *.map file which can optionally be generated by the linker when it links the program, or at the program's debug (*.pdb) file.
OK, I haven't done assembly in about 15 years. Back then, I didn't do very much. Also, it was 680x0 asm. BUT...
Don't you just need to put a label before and after the function, take their addresses, subtract them for the function length, and then just compare the IP? I've seen the former done. The latter seems obvious.
If you're doing this in C, look first for debugging support --- ChrisW is spot on with map files, but also see if your C compiler's standard library provides anything for this low-level stuff -- most compilers provide tools for analysing the stack etc., for instance, even though it's not standard. Otherwise, try just using inline assembly, or wrapping the C function with an assembly file and a empty wrapper function with those labels.
The most simple solution is maintaining a state variable:
volatile int FOO_is_running = 0;
int Foo( int par ){
FOO_is_running = 1;
/* do the work */
FOO_is_running = 0;
return 0;
}
Here's how I do it, but it's using gcc/gdb.
$ gdb ImageWithSymbols
gdb> info line * 0xYourEIPhere
Edit: Formatting is giving me fits. Time for another beer.