I have created a library in C++ in which I have a function similar to the following:
originalmain.cpp
executionTimer * timer;
//This function is available to every other class through a global header file
calculateTime(){
timer->returnTime()
}
main(){
foo(); // a function that eventually calls calulateTime()
return 0;
}
foo.cpp
#include "globals.h"
void foo(){
....
calculateTime();
...
When foo() calls calculateTime(), the global function defined in main.cpp executes.
I have created a library from those files which I'm using in another program like so:
mymain.cpp
#include "globals.h"
// trying to redefine the executionTime global object
// and the global calculateTime function to use it
executionTime * timer2;
calculateTime(){
timer2->returnTime()
}
main(){
foo(); // I want foo to run normally, but now use timer2 instead of timer
...
return 0;
}
From my understanding, since I'm using the library, I should have access to the functions/classes etc defined there. and indeed I have in most of them.
Things go wrong when foo() is calling 'calculateTime'. In that case I would expect calculateTime() from mymain.cpp to be executed, but instead I see the one from main.cpp.
So I have the following questions:
Why is this happening?
Is there a way to fix it?
Best regards
Related
I'm the beginner with C++.
Could some one explain the output after compile process function.
Thanks a lot.
template <typename T>
auto process(T arg)
{
// 4. With constexpr if, to enable the compiler to generate different code based on the type the template is instantiated with:
if constexpr (std::is_same<T, bool>::value)
return !arg;
else if constexpr (std::is_integral<T>::value)
return -arg;
else if constexpr (std::is_floating_point<T>::value)
return std::abs(arg);
else
return arg;
}
int main(){
...
{
auto v1 = process(false); // true
auto v2 = process(42); // -42
auto v3 = process(-42.0); // 42.0
auto v4 = process("42"s); // "42"
}
...
return 0;
}
what's the real code compiler for process() is generated after we call above code in main function.
what's the real code compiler for process() is generated after we call above code in main function.
process() is not a function, and no compiled version of it is produced (at least in typical implementations); rather, your program produces four separate functions, namely process<bool>, process<int>, process<double>, and process<std::string>, each of which has its own compiled version.
And that's not specific to if constexpr — it's just how templates work in general in C++.
Those compiled versions can completely omit the branches of the if statement that don't hold for the type argument; so, for example, process<bool> is as if it were defined like this:
template<>
bool process<bool>(bool arg)
{
return !arg;
}
I'm writing some code that would greatly benefit from the concise syntax of lambdas, which were introduced with C++ 11. Is this supported by the compiler?
How do I specify the compiler flags when compiling using Energia or embedXcode?
As of February 2018, up to C++14 is supported with some limitations:
http://processors.wiki.ti.com/index.php/C%2B%2B_Support_in_TI_Compilers
There isn't much about this topic on the TI site, or, at least, I don't know enough C++ to give you a detailed and precise response.
The implementation of the embedded ABI is described in this document that is mainly a derivation of the Itanium C++ ABI. It explains nothing about the implementation of lambdas nor the auto, keyword (or probably I'm not able to derive this information from the documentation).
Thus I decided to directly test in Energia. Apparently the g++ version is 4.6.3, thus it should support both.
And in fact (from a compilation point of view, I don't have my MSP here to test the code) it can compile something like:
// In template.hpp
#ifndef TEMPLATE_HPP_
#define TEMPLATE_HPP_
template<class T>
T func(T a) {
auto c = [&](int n) { return n + a; };
return c(0);
}
#endif /* TEMPLATE_HPP_ */
// in the sketch main
#include "template.hpp"
void setup() { int b = func<int>(0); }
void loop() { }
(the template works only if in an header, in the main sketch raises an error). To compile this sketch I had to modify one internal file of the editor. The maximum supported standard seems to be -std=c++0x, and the compilation flags are in the file:
$ENERGIA_ROOT/hardware/energia/msp430/platform.txt
in my setup the root is in /opt/energia. Inside that file I modified line 32 (compiler.cpp.flags) and added the option. Notice that -std=c++11 is not supported (raises an error).
compiler.cpp.flags=-std=c++0x -c -g -O2 {compiler.mlarge_flag} {compiler.warning_flags} -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD
Unfortunately I have zero experience with embedXcode :\
Mimic std::function
std::function is not provided, thus you have to write some sort of class that mimics it. Something like:
// callback.hpp
#ifndef CALLBACK_HPP_
#define CALLBACK_HPP_
template <class RET, class ARG>
class Callback {
RET (*_f)(ARG);
public:
Callback() : _f(0) { };
Callback(RET (*f)(ARG)) : _f(f) { };
bool is_set() const { return (_f) ? true : false; }
RET operator()(ARG a) const { return is_set() ? _f(a) : 0; }
};
#endif /* CALLBACK_HPP_ */
// sketch
#include "callback.hpp"
// | !! empty capture!
void setup() { // V
auto clb = Callback<int, char>([](char c) { return (int)c; });
if (clb.is_set())
auto b = clb('a');
}
void loop() {}
may do the work, and it uses a simple trick:
The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. [C++11 standard 5.1.2]
As soon as you leave the capture empty, you are assured to have a "conversion" to a function pointer, thus you can store it without issues. The code I have written:
requires a first template RET that is the returned type
requires a second template ARG that is one argument for the callback. In the majority of the case you may consider to use void* as common argument (cast a struct pointer in a void pointer and use it as argument, to counter-cast in the function, the operation costs nothing)
implements two constructors: the empty constructor initialize the function pointer to NULL, while the second directly assigns the callback. Notice that the copy constructor is missing, you need to implement it.
implements a method to call the function (overloading the operator ()) and to check if the callback actually exists.
Again: this stuff compiles with no warnings, but I don't know if it works on the MSP430, since I cannot test it (it works on a common amd64 linux system).
I wrote this code and compile with gcc.
I expected to get result "2", but result was "0".
Other compiler clang and vc prints "2".
Is it undefined behaviour or not?
#include <stdio.h>
struct Test {
Test& inc() {
++value;
return *this;
}
int value = 1;
};
int main() {
auto&& t = Test().inc(); // The life-time of the temporary might extended.
printf("%d\n", t.value); // gcc prints "0". dangling reference?
return 0;
}
c.f. build reslut on http://rextester.com
gcc result
clang result
vc result
The forwarding reference (that's what universal references have been renamed to) is irrelevant -- you would observe the same behaviour with a regular reference.
The issue is that the Test's lifetime is not extended, because it is not directly bound to the reference, as auto &&t = Test(); would be. Instead, its member function returns an lvalue reference, which is used to deduce and initialize t as a Test & (you can check this via decltype(t)). Then the temporary is destructed, the reference is now dangling, and using it is undefined behaviour.
If I have a pure virtual class InterfaceA that consists solely of a pure virtual destructor, why do I have to define the destructor as inline? I I don't I get an error when I try to link it.
Below is an admittedly contrived example, however it illustrates the point. The point does not compile for me using cmake and g++. However, if I change the InterfaceA destructor definition as follows - inline InterfaceA::~InterfaceA(){}; then it compiles.
Why is this? What does the inline keyword do?
// InterfaceA.h, include guards ommitted for clarity
class InterfaceA
{
public:
virtual ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA(){};
// A.h, include guards ommitted for clarity
#include "InterfaceA.h"
class A : public InterfaceA
{
public:
A(int val)
: myVal(val){};
~A(){};
int myVal;
};
// AUser.h, include guards ommitted for clarity
#include "InterfaceA.h"
class AUser
{
public:
AUser(InterfaceA& anA)
: myA(anA){};
~AUser(){};
int getVal() const;
private:
InterfaceA& myA;
};
// AUser.cpp
#include "AUser.h"
#include "A.h"
int AUser::getVal() const
{
A& anA = static_cast<A&>(myA);
return anA.myVal;
}
// main.cpp
#include "AUser.h"
#include "A.h"
#include <iostream>
int main(){
A anA(1);
AUser user(anA);
std::cout << "value = " << user.getVal() << std::endl;
return 0;
}
You have to use the inline keyword when defining functions in header files. If you do not, and the file is included in more than one translation unit, the function will be defined twice (or more times).
The linker error is probably something like "Symbol ... is multiply defined" right?
If you defined the member function in the body of the class, it would be implicitly inline and it would also work.
See this answer
To answer the question "What does the inline keyword do?":
In the old days it would be used to ask the compiler to inline functions i.e. insert the code whenever the function is used instead of adding a function call. Eventually it turned into a simple suggestion since compiler optimizers became more knowledgeable about which functions were inline candidates. These days it is used almost exclusively to define functions in header files that must have external linkage.
inline means that compiler is allowed to add code directly to where the function was called. It also removes function from external linkage, so both your compile units would have local version of.. pure destructor.
// InterfaceA.h, include guards ommitted for clarity
class InterfaceA
{
public:
virtual ~InterfaceA() = 0;
};
You declare destructor virtual, so compiler almost never would make it inline. Why? because virtual functions are called through vtable - a internal working of virtual functions system, vtable most likely implemented as an array of pointers to member functions. If function is inlined, it would have no address, no legal pointer. If attempt to get address of function is taken, then compiler silently disregards inline keyword. The other effect will be still in place: inlined destructor stops to be visible to linker.
It may look like declaring pure virtual destructor looks like oxymoron , but it isn't. The pure destructor is kind of destructor that would be always called without causing UB. Its presence would make class abstract, but the implicit call in sequence of destructor calls would still happen. If you didn't declare destructor body, it would lead to an UB, e.g. purecall exception on Windows.
If you don't need an abstract base class, then inline definition will suffice:
class InterfaceA
{
public:
virtual ~InterfaceA() {}
};
that is treated by compiler as inline as well, but mixing inline definition and pure member declaration is not allowed.
In many places i have code for one time initialization as below
int callback_method(void * userData)
{
/* This piece of code should run one time only */
static int init_flag = 0;
if (0 == init_flag)
{
/* do initialization stuff here */
init_flag = 1;
}
/* Do regular stuff here */
return 0;
}
just now I started using c++11. Is there a better way to replace the one time code with c++11 lambda or std::once functionality or any thing else?.
You can encapsulate your action to static function call or use something like Immediately invoked function expression with C++11 lambdas:
int action() { /*...*/ }
...
static int temp = action();
and
static auto temp = [](){ /*...*/ }();
respectively.
And yes, the most common solution is to use std::call_once, but sometimes it's a little bit overkill (you should use special flag with it, returning to initial question).
With C++11 standard all of these approaches are thread safe (variables will be initialized once and "atomically"), but you still must avoid races inside action if some shared resources used here.
Yes - std::call_once, see the docs on how to use this: http://en.cppreference.com/w/cpp/thread/call_once