Author Topic: Taking a C++ class, looking for a C++14 compatible microcontroller to play with.  (Read 26368 times)

0 Members and 1 Guest are viewing this topic.

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Hi,

I'm taking a C++ programming course at my local college and I'm wondering which microcontrollers I can program with C++14 or C++11 for practice and experimentation. Support for the Standard Library, STL, and/or Boost would be nice. Would prefer a development or prototyping board that has I/O headers.

The size of the programs I've created so far average 450KB compiled on my mac. So I'm guessing I would need 1MB+ of flash?
« Last Edit: October 15, 2016, 01:04:31 am by nbritton »
 

Offline Franc

  • Regular Contributor
  • *
  • Posts: 64
  • Country: br
Atmel SAM D in AS7 ..
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Atmel SAM D in AS7 ..

The Arduino Zero has a SAM D21, would you recommend this board?

https://www.arduino.cc/en/Main/ArduinoBoardZero
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
It doe not matter at all. Any MCU with GCC support will work.

But if you are just taking the class, do you want to pile up figuring embedded programming at the same time? Programming for embedded device is quite a bit different from programming desktop applications.

And with STL and Boost you won't get far in the embedded world.
Alex
 
The following users thanked this post: janoc, elgonzo, rs20, nugglix

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9890
  • Country: us
^^^ What he said!

I would want to program the C++ stuff for the PC.  I don't care whether it is a command line program for Windows or whether it targets Linux but I sure wouldn't want to try to get up to speed on embedded programming with an application that is that large.  You could target the Raspberry PI, I suppose.  That's a full blown Linux system on a board and, while you can do some 'sort of' embedded programming, you don't have to.  There are Python examples of embedded stuff included in the distribution (IIRC).

 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
But if you are just taking the class, do you want to pile up figuring embedded programming at the same time?

And with STL and Boost you won't get far in the embedded world.

I thought I did, I was thinking I could knock out two birds with one stone. I work as a Linux systems engineer so I'm thinking I can translate that skillset to figuring out embedded programming. Also, the C++ course I'm taking is all console based programming.

In fact, maybe a little embedded ARM prototyping board running Linux would be what I'm looking for? Can I install gcc on the Raspberry Pie?
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Also, the C++ course I'm taking is all console based programming.
Well, in embedded world there is not even a console :)

In fact, maybe a little embedded ARM prototyping board running Linux would be what I'm looking for?
Depends on what you want to do. Programming for Linux on RPi is not all that different from programming for desktop Linux. And If you don't have a project that actually warrants the use of RPi, then it is a waste of time, just program for desktop. And programming for RPi is very-very different from programming MCUs with no OS or with RTOS.

Can I install gcc on the Raspberry Pie?
Yes, you can. It runs full Debian, you can install anything you like.
Alex
 

Offline ez24

  • Super Contributor
  • ***
  • Posts: 3082
  • Country: us
  • L.D.A.
Can I install gcc on the Raspberry Pie?
Sounds good, but I never had one.  Has anyone ever eaten a raspberry pie?
YouTube and Website Electronic Resources ------>  https://www.eevblog.com/forum/other-blog-specific/a/msg1341166/#msg1341166
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
There are Python examples of embedded stuff included in the distribution (IIRC).

Yeah, that reminds me! I'm taking a Python class too, so I would want to be able to program using that too. Perhaps what I actually need is a Linux prototyping board that has some GPIO, SPI, and I2C headers? I still would like to get into microcontroller programming though.
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Perhaps what I actually need is a Linux prototyping board that has some GPIO, SPI, and I2C headers?
That's a RPi.

I still would like to get into microcontroller programming though.
That's something entirely different and you better get used to programing in plain C. Majority of advanced C++ features are way too expensive on MCUs.
Alex
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Perhaps what I actually need is a Linux prototyping board that has some GPIO, SPI, and I2C headers?
That's a RPi.

I still would like to get into microcontroller programming though.
That's something entirely different and you better get used to programing in plain C. Majority of advanced C++ features are way too expensive on MCUs.

What about something like the Intel Edison or Galileo? Would that teach me more about what's going on under the hood? One of my goals is learning more about everything that is going on between the bare hardware and the operating system, so the thing that appeals to me about the Intel boards is that they're based on the x86 based ISA.

Mastering C is on my bucket list, but for the next few months I'm focused exclusively on C++11 and Python.
« Last Edit: October 15, 2016, 01:50:40 am by nbritton »
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
What about something like the Intel Edison? Would that teach me more about what's going on under the hood? One of my goals is learning more about everything that is going on between the bare hardware and the operating system, so the thing that appeals to me about the Intel Edison is it's based on the x86 based ISA.
You are programming in high level language, what do you care what ISA your MCU has?

Intel Edison is a pretty pointless thing. It is very restrictive on available memories and has no features that would make it attractive for any practical use.

Industry standard for embedded things right now is ARM, and if you want to get some useful practical skill, then learn ARM.

Mastering C is on my bucket list, but for the next few months I'm focused exclusively on C++11 and Python.
Then do desktop stuff first. C is basically the same as C++ if you don't use classes.
Alex
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Industry standard for embedded things right now is ARM, and if you want to get some useful practical skill, then learn ARM.

Agreed. However, I work with commodity Linux servers and x86 is the only player in this market. In fact, the company I work for has a strategic partnership with Intel.
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Agreed. However, I work with commodity Linux servers and x86 is the only player in this market. In fact, the company I work for has a strategic partnership with Intel.
That's fine, but what MCUs have to do with that?

You can program regular computers on a low level - just look at the code of any Linux loader (LiLo, GRUB). Then take QEmu or VirtualBox and do x86 programming on a low level all you want.

Edison is an x86 core slapped on top of mediocre MCU peripherals, it is nothing like programming actual real x86 hardware.
Alex
 

Offline kc8apf

  • Regular Contributor
  • *
  • Posts: 103
  • Country: us
What you use for desktop or server isn't relevant for embedded work. There's basically no overlap in ISA between the two worlds.

Sent from my Nexus 5X using Tapatalk

 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Edison is an x86 core slapped on top of mediocre MCU peripherals, it is nothing like programming actual real x86 hardware.

What do you think of the MinnowBoard Max? It sounds like what I need then is real x86 hardware, but with the addition of GPIO and SPI headers that I can program with C++ or Python. At home I'm all Apple and Mac OS X on my desktops, so I can't (read don't want to) play with them. I think maybe what I really want is just a little low wattage box that I can SSH into wirelessly that has some GPIO headers and SPI and I2C buses I can play with.
« Last Edit: October 15, 2016, 02:41:32 am by nbritton »
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
What do you think of the MinnowBoard Max?
Never heard of it, but looks like a decent board.

But if you are going this route, then why not RPi? At no point you will actually see that it is an ARM processor. Same as you will never know that it is an x86 with MinnowBoard.

Using those interfaces from Python sounds more likely on RPi than on MinnowBoard.
« Last Edit: October 15, 2016, 03:47:21 am by ataradov »
Alex
 

Offline Ian.M

  • Super Contributor
  • ***
  • Posts: 12860
Yes, there's a *LOT* to be said for sticking with mainstream hardware, and the Pi is about as mainstream as it gets for consumer SBCs.  Get a PI 3 to develop on then if you want to integrate it into anything consider a Pi Zero to deploy with.

Also why not try an Arduino?  The Uno is the most popular entry level one and you'll soon get a feel for how much of C++ is practical on a small MCU with only 2K RAM.  Its very easy to ditch the Arduino setup()/loop() stuff* and code in raw GCC C++, either with the simplified Arduino HAL, or digging deeper and using the raw AVR registers and libraries.  Once you've mastered that, porting to any ATmega MCU is fairly simple.

Both platforms have plenty of good breadboardable tutorials to cover the interfacing side of things.

* see http://www.gammon.com.au/forum/?id=12625
« Last Edit: October 15, 2016, 06:32:57 pm by Ian.M »
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Hardware wise, what would it take to run the code below?... it uses the new c++11 <random> library.

Quote
#include <iostream>
#include <random>
#include <type_traits>
#include <thread>

using namespace std;

template < typename T > inline T get_random_number( T min, T max ) {
   
    static_assert( std::is_arithmetic<T>::value, "expected integral or floating point type" ) ;
   
    static std::mt19937_64 generator ( std::chrono::steady_clock::now().time_since_epoch().count() );
   
    using uniform_distribution = typename std::conditional< std::is_integral<T>::value,
                                                            std::uniform_int_distribution<T>,
                                                            std::uniform_real_distribution<T> >::type ;
   
    std::this_thread::sleep_for( std::chrono::nanoseconds(1) );
   
    return uniform_distribution(min, max) (generator);
}

int main(int argc, const char * argv[]) {
   
    while (true) {
        cout << get_random_number<int>(0, 1);
    }
    return 0;
}
« Last Edit: October 15, 2016, 04:53:14 am by nbritton »
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
This is very hardware-independent, so any platform with reasonably recent GCC will run this without any problems.

This will definitely work on RPi.
Alex
 

Offline asgard20032

  • Regular Contributor
  • *
  • Posts: 184
Does some general purpose mcu (not talking about high end blackfin), like avr, pic, mps430, arm cortex... has some random number generator?
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Correction. It will compile on RPi, whether it will work is not guaranteed, apparently.

I don't have a free RPi at the moment, but I do have Atmel SAMA5D3 Xplained board (still runs Linux).

This program compiles but hangs when you run it.

I'll try to debug a bit. It may lack a source of entropy.
« Last Edit: October 15, 2016, 05:25:38 am by ataradov »
Alex
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Does some general purpose mcu (not talking about high end blackfin), like avr, pic, mps430, arm cortex... has some random number generator?
Some do, but most don't.  At the same time they all have lots of peripheral that can be used for random number generation (ADC noise, random content of the RAM on power up, variable time it takes to write a EEPROM value, etc).
Alex
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Yes, so the program above works. It was console buffering that held the output.

With modification like this:
Code: [Select]
    while (true) {
        cout << get_random_number<int>(0, 1) << "\n";
    }
it prints random numbers right away.

[pardon for "\n", I'm not into screwed up C++ standard output stuff]
Alex
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Yes, so the program above works.

Cool. How much space did it take up? I'm still trying to get a feel for how big the binaries are that the compiler makes. Could this fit and run on an Ardunio Micro, Pro Mini, Uni, or Mega? I have all of those boards.
« Last Edit: October 15, 2016, 06:03:35 am by nbritton »
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Cool How much flash space did it take up?
20 KB. It obviously uses a lot of dynamic libraries, which are probably taking dozens of megabytes.

I'm still trying to get a feel for how big the binaries are that the compiler makes. Could this fit and run on an Ardunio Micro, Pro Mini, Uni, or Mega? I have all of those boards.

You are confusing things. The board I was using runs Linux, it is nowhere close to Arduino stuff. It is like Raspberry Pi.

AVR compiler does not support STL, so you are out of luck there. Again, you need plain C for those boards.

Here is what happens if you try to compile that madness with AVR GCC:
Quote
alexru:/tmp/2$ avr-g++ -std=c++11 r.cpp
r.cpp:1:20: fatal error: iostream: No such file or directory
You get the idea :)
« Last Edit: October 15, 2016, 06:03:43 am by ataradov »
Alex
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Alright, thanks for your help, I just bought a Raspberry Pi 3 Model B.
 

Offline JPortici

  • Super Contributor
  • ***
  • Posts: 3461
  • Country: it
Does some general purpose mcu (not talking about high end blackfin), like avr, pic, mps430, arm cortex... has some random number generator?
of course.
a lot of the newer pic offerings (i think even from pic16 up to pic32) has either a PRNG or a TRNG. if not explicitely noted look in the oscillator section, you may have a "random" register that can be used by the MCU to implement frequency hopping of the internal oscillator
cortex M4 has a TRNG, but that may be vendor-dependant
 

Offline Dubbie

  • Supporter
  • ****
  • Posts: 1115
  • Country: nz
Alright, thanks for your help, I just bought a Raspberry Pi 3 Model B.

Finally!
I thought you were never going to take Ataradov's advice.


Sent from my iPhone using Tapatalk
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
If you want to get a leg-up on the other people on the course, read learn and inwardly digest the C++ FQA (no typo). While not updated to C++14, it is still highly relevant and highly amusing.

See http://yosefk.com/c++fqa/
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline gmb42

  • Frequent Contributor
  • **
  • Posts: 294
  • Country: gb
If you want to get a leg-up on the other people on the course, read learn and inwardly digest the C++ FQA (no typo). While not updated to C++14, it is still highly relevant and highly amusing.

See http://yosefk.com/c++fqa/

Another run of your standard trope to C++ questions.  Meanwhile, many folks are actually using C++ (along with many other languages) for millions of applications that actually do something useful.  Some even pass all their tests and run for decades (I'm not joking here, stuff I wrote in the 90's is still in use in the field) and haven't blown up yet.

Of course, sometimes I run into problems, mostly logical errors in my own code, occasionally a compiler\library bug, and once in a blue moon a language issue.  None of these problems are exclusive to C++.
 
The following users thanked this post: lukier

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Alright, thanks for your help, I just bought a Raspberry Pi 3 Model B.

Finally!
I thought you were never going to take Ataradov's advice.

It was great advice. As a beginner, it's really the only choice because it has the most educational resources due to its ubiquity. I was really interested in a x86 device, but as far as I can tell only the Intel Edison has WiFi. The deciding factor for me was that it has WiFi and Bluetooth to connect my wireless keyboard, and that it was cheap.

I still would like to find an x86 ISA board that I can use as a trainer for learning more about how the platform works at the component level and how the hardware interacts with the operating system. One of my long term goals is to make my own rudimentary computer from scratch using discrete components.
« Last Edit: October 15, 2016, 02:39:05 pm by nbritton »
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
And with STL and Boost you won't get far in the embedded world.
I wouldn't rule out anything right off the bat because it could be bloated or slow. At the end of the day what counts is whether it works perfectly and is finished in a reasonable timeframe. For example: In a DSP project I used soft floating point because it was fast enough to get the job done.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
If you want to get a leg-up on the other people on the course, read learn and inwardly digest the C++ FQA (no typo). While not updated to C++14, it is still highly relevant and highly amusing.

See http://yosefk.com/c++fqa/

Another run of your standard trope to C++ questions.  Meanwhile, many folks are actually using C++ (along with many other languages) for millions of applications that actually do something useful.  Some even pass all their tests and run for decades (I'm not joking here, stuff I wrote in the 90's is still in use in the field) and haven't blown up yet.

Of course, sometimes I run into problems, mostly logical errors in my own code, occasionally a compiler\library bug, and once in a blue moon a language issue.  None of these problems are exclusive to C++.

C is a 44 year old programming language and C++ is 33 years old. The world's first stored-program computer (Manchester) was created in 1948, which was only 68 years ago. So C was created only 24 years after that. It took us 60 years from first flight by the Wright brothers until we got into space. You have to keep that in perspective before complaining about the language, in its day it was an awesome language and it helped to build the foundation of world we know today. With the additions of C++11, C++14, and the upcoming C++17 I believe the language can stay relevant. C and C++ is about as close as most people want to get to the hardware so I don't see them going away any time soon. The modern human is about 200,000 years old, so 68 years represent a fraction of a blip on that time scale... computers are still in their infancy.
« Last Edit: October 15, 2016, 05:25:43 pm by nbritton »
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
computers are still in their infancy.

it's also interesting that fourth-order languages
like "Prolog" (PROgrammation en LOGique)
haven't grown in their popularity and currently
almost used for AADL's purposes (e.g. "Stood")


!:: computers are still in their infancy
-> artificial intelligence is not born yet

 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
If you want to get a leg-up on the other people on the course, read learn and inwardly digest the C++ FQA (no typo). While not updated to C++14, it is still highly relevant and highly amusing.

See http://yosefk.com/c++fqa/

Another run of your standard trope to C++ questions.  Meanwhile, many folks are actually using C++ (along with many other languages) for millions of applications that actually do something useful.  Some even pass all their tests and run for decades (I'm not joking here, stuff I wrote in the 90's is still in use in the field) and haven't blown up yet.

Of course, sometimes I run into problems, mostly logical errors in my own code, occasionally a compiler\library bug, and once in a blue moon a language issue.  None of these problems are exclusive to C++.

Unfortunately almost as many are misusing c/c++, usually through ignorance of its misfeatures.

Don't forget that the second book on C in 1981 (The C Puzzle Book) detailed it's few "idiosyncrasies", and it has got much worse since then. In the early 90s even the language designers didn't understand what they had created. (Yes, I still have both K&R and The Puzzle Book; it is worrying to realise I first used C professionally 35 years ago).

The c++ fqa is invaluable not only for beginners but those that think they know the language.
« Last Edit: October 15, 2016, 06:51:59 pm by tggzzz »
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9890
  • Country: us
C is a 44 year old programming language and C++ is 33 years old. The world's first stored-program computer (Manchester) was created in 1948, which was only 68 years ago. So C was created only 24 years after that.

C is still around because it serves its purpose better than anything that has come along.  Major projects, like the Linux kernel, are still being written in C.

Fortran is even older than C but it is still in use in the scientific community because it serves its purpose better than anything that has come along.  It's a simple language which means it is easy to learn and apply.  When you want a fast answer to an arithmetic problem, Fortran is still the way to get it.  I have been using it when providing sidebar explanations for my grandson's math courses.  I will make certain he learns how to write Fortran code over the Thanksgiving break.  It's a tool, just like a calculator.  I rather like the extensions over Fortran IV where they have cleaned up the IF and DO statements.

I have yet to try gfortran against one of the embedded (ARM) versions of gcc.  Wouldn't that be cool?  Image processing on a robot coded in Fortran.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
C is a 44 year old programming language and C++ is 33 years old. The world's first stored-program computer (Manchester) was created in 1948, which was only 68 years ago. So C was created only 24 years after that.

C is still around because it serves its purpose better than anything that has come along. 

That's very debatable; never underestimate the power of inertia. Hence COBOL :)

Nowadays the critical factor isn't the C/C++ language(s) per se, rather it is the accumulated development environments and libraries, and upfront financial cost.

Quote
Major projects, like the Linux kernel, are still being written in C.

Well of course it is! Nobody in their right mind would rewrite it in another language.

Quote
Fortran is even older than C but it is still in use in the scientific community because it serves its purpose better than anything that has come along.  It's a simple language which means it is easy to learn and apply.  When you want a fast answer to an arithmetic problem, Fortran is still the way to get it.  I have been using it when providing sidebar explanations for my grandson's math courses.  I will make certain he learns how to write Fortran code over the Thanksgiving break.  It's a tool, just like a calculator.  I rather like the extensions over Fortran IV where they have cleaned up the IF and DO statements.

Agreed.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
And with STL and Boost you won't get far in the embedded world.

 :-DD Tell me why I cannot get far in the embedded world, even on an 8 bit MCU, with such "horrible" STL/Boost things: std::array, std::pair, std::tuple, std::fill, std::is_same, boost::circular_buffer, boost::crc and so on.

These are pretty much pure templates, no new/delete, no exceptions or can be disabled, the compiler optimizes out everything leaving very compact output binary (or nothing in the binary, as some things like std::is_same are only compile time). I think people don't realize how good C++ compilers became in the last 1-2 decades. And in the exceptionally very rare cases one can always study the resulting assembly and may hint the compiler to do the right thing anyway, without resorting to the inline assembly.

Also there is embedded and there is embedded, sometimes people think everything is ATtiny. I once worked in a mission critical project (core network switch, total switching 6 Tbit/s) where our system was running on 14 cards, each one with dual core 1GHz PowerPC and 2GB RAM (some of the cards were control cards, one card active, one sleeping and taking over if the primary fails - extra redundancy).

The system was complex, written in C++, but with RT-allocator and Xenomai where needed. The management decided we cannot use STL because: "STL is not for embedded". Instead they've decided to get some people to develop "in-house" STL containers alternative. After a lot of time and corporate money they've came up with C++ classes operating on void pointers and even the simple vector there was 20% slower than the STL one, not to mention the bugs there (STL is tested for decades everywhere).

C is still around because it serves its purpose better than anything that has come along.  Major projects, like the Linux kernel, are still being written in C.

Historical reasons and Linus' personal animosity towards C++, probably related to the former. When Linux was started C++ wasn't that mature, compilers buggy and the UNIX tradition has always been K&R C.

AFAIR Linus's argument against C++ was dynamic memory management (new/delete) and exceptions. For my embedded projects I disable exceptions (binary size too big for small MCUs) and either don't use heap (small stuff) or put TLSF allocator (real-time) underneath new/delete operators - problem solved.

I did some kernel development and when you start learning Linux codebase the lack of C++ syntax screams at you everywhere, for example:
  • containers done with void pointers and macros (e.g. INIT_LIST_HEAD) - yay type safety,
  • polymorphism, virtual functions and object hierarchies done with structs with function pointers that have to be manually set (e,g, ethtool_ops), pointer arithmethic to get private data (e.g. netdev_priv) and other horrid constructs
  • instead of exceptions we get a ton of error prone gotos and return codes

Of course no one in the right mind would now start rewriting Linux to C++, it would be a tremendous effort. I think there were plans to rewrite GCC to C++, but I don't know what's the current status. Richard Stallman (original author of GCC) is another anti-C++ dinosaur. Of course it is perfectly possible to write a good compiler in C++, LLVM/Clang is the proof.

I don't get this C/C++ argument at all. C++ supports C as well and one can do stupid things in both languages. If someone is not fluent in C++ and writes embedded code with heavy use of heap (and with non-RT allocator), incorrectly uses exceptions (for program flow) or god knows why uses RTTI then it is not the language to blame. One can do stupid stuff in C, pulling in size-heavy glibc functions, dynamic memory on void pointers and ignore type safety.

I personally use C++ everywhere, from small MCU to large multithreaded image processing apps, either on the CPU or nVidia CUDA and I absolutely love strong type safety and template metaprogramming in all of these platforms. Just, as any other skilled worker, know your tools and libraries.
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
:-DD Tell me why I cannot get far in the embedded world, even on an 8 bit MCU, with such "horrible" STL/Boost things: std::array, std::pair, std::tuple, std::fill, std::is_same, boost::circular_buffer, boost::crc and so on.
Because of this:

For my embedded projects I disable exceptions (binary size too big for small MCUs) and either don't use heap (small stuff) or put TLSF allocator (real-time) underneath new/delete operators - problem solved.
......
If someone is not fluent in C++ and writes embedded code with heavy use of heap (and with non-RT allocator), incorrectly uses exceptions (for program flow) or god knows why uses RTTI then it is not the language to blame.

You really-really need to know what you are doing. And it is very clear that OP does not at the moment.

It is like asking "can I drive safely without seat belts". You can under certain conditions, but in most cases, if you don't know exactly what you are doing, you should not.

Also, C++ projects tend to bloat if there is no control. If you are working in a team, over time, people start using more and more of nice, but expensive features of  C++. If you work alone, you can control that. If you work on a team - not necessarily.
Alex
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
instead of exceptions we get a ton of error prone gotos and return codes

this part looks interesting  :D
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
I mean those "exceptions features" have been a part of C++
since early 90s (correct?) and are sanctioned by the standard
to be *THE* mechanism for writing fault-tolerant code
however, many developers for various reasons choose not to use
exceptions, and voices that are skeptical of this language feature
are still numerous and loud  :-//

 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
IMHO the problem with exceptions is that you still need to handle the error in a gracefull manner otherwise it is just a nice way to crash. When used to catch an error an exception is very similar to (for those familiar with Basic) 'on error goto...'
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Google C++ Style Guide are some of the frequently
quoted texts that advise against the use of exceptions.

on the other way, exceptions are hard to ignore, unlike error
codes, and easily propagated from deeply nested functions

but, Exceptions break code structure by creating multiple
invisible exit points that make code hard to read and inspect

and they easily lead to resource leaks, especially in a language
that has no built-in garbage collector and finally blocks.

( should a kernel have a garbage collector ? no sense  :-// )

also, from the implementation point of view,  Exceptions are also
expensive and break the promise to pay only for what you use.
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
You really-really need to know what you are doing. And it is very clear that OP does not at the moment.

That's maybe true, but then you think one cannot shoot themself in the foot in C? OP needs to learn, doesn't matter if C or C++. This is not a C++ problem :)

Also, C++ projects tend to bloat if there is no control. If you are working in a team, over time, people start using more and more of nice, but expensive features of  C++. If you work alone, you can control that. If you work on a team - not necessarily.

You have no idea how serious the development process is in mission critical projects. First of all there is way more documentation & paperwork then the code itself, then very strict coding standards (see MISRA or Joint Strike Fighter) and the available language features and libraries are set by the architects, fixed in the Board Support Package or similar construct project-wide and there is no way you'll pull your own "cool think" into the codebase.

Also, you cannot merge your branch into the mainline of the project without a dozen of signatures, from code review to approvals on unit tests and component tests from the testing/integration team, static & dynamic code analysis results, automated coding standard compliance verification to paperwork like release notes and other traceability related stuff. And then in the next project internal release cycle the performance integration testing team will come back to you if there are problems with performance.

That's why I laughed when it was in the news that the VW emissions was just a thing done by few engineers without anyone knowing. No f... way.

Also, as I mentioned before, in this case "embedded" didn't mean resource constrained and STL containers would be perfectly acceptable.

this part looks interesting  :D

I know exceptions are difficult. That's probably one of two C++ features (another being RTTI) where I don't object if people say to turn them off. I do that myself for MCU projects, because exception handling adds 65KB to my binary.

On less resource constrained platforms I prefer exceptions and RAII design pattern to a litany of gotos and labels like in Linux kernel and forgetting to manually release some resource in each of the 10 gotos in a function. Also, there are some myths around exceptions, for example some people think that using exceptions impacts performance. This is not true, currently exceptions are implemented with Zero-Cost model and if there is no exception there is no performance penalty.

Google C++ Style Guide are some of the frequently
quoted texts that advise against the use of exceptions.

Google C++ Style Guide is horrible and I think the intentions were as such: 1) we have 100 mln lines of current bad code, so let's keep writing more bad code, 2) we don't expect fresh undergrads to know C++ well, we cannot afford skilled people in large numbers, so let's work our way around that.

The dogmatic lack of exceptions creates another problems in this style guide (e.g. constructors are bad etc).
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
just a nice way to crash

especially if you feel there is a lack of "discipline"
in your development team  :-//

I mean learning to write Exception safe code is hard
and, still worse, is hard to introduce to legacy code
(not mentioning that it's hard for the testing team)
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
You have no idea how serious the development process is in mission critical projects.
I do, but most projects are not "mission critical" and you don't have a luxury of rigorous code review.
Alex
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
I do, but most projects are not "mission critical" and you don't have a luxury of rigorous code review.

Again, nothing to do with C++ as such.

I'm quite militant on this C/C++ issue because there is a ton of people in the embedded world that either don't know C++ that well or tried a bit of  C++ in the early nineties when it was buggy. It doesn't stop them from spreading the misinformation that persists after 2 decades. Myths abouts runtime performance of exceptions (by people that use exceptions for control flows or non-critical errors), that virtual functions are slow (your series of ifs or a switch statement in C is probably slower than a C++ call table), that C++ produces huge binaries (C++ compilers are extremely good nowadays and Template Metaprogramming alows code that runs in the compile time, possibly generating no assembly at all) and so on.

C++ combines nice OO and sometimes unique (template metaprogramming) features while being as close to the metal as C, this gives tremendous possibilities. I agree that exceptions are problematic and C++ has a steep learning curve, but in C++ you can always write your C code, just it's nothing to be proud about :).
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
@lukier
I see the UK flag in your profile: Cheltenham?
I happen to have some collaborations there, but it's C only
things like bpum, BSP, iBSP, Automa, and some drivers
nothing as complex as the AFDX lan-switch (was it?)
on which you have probably worked

frankly, when you say C++ I have a thrill of genuine fear
if I let my mind thinking about tools like Vectorcast
applied to C++, in a mission critical environment
with exceptions enabled ( God save the Queen  :D )
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
@lukier
I see the UK flag in your profile: Cheltenham?
I happen to have some collaborations there, but it's C only
things like bpum, BSP, iBSP, Automa, and some driver
nothing as complex as the AFDX lan-switch (was it?)
on which you have probably worked

frankly, when you say C++ I have a thrill of genuine fear
if I let my mind thinking about tools like Vectorcast
applied to C++, in a mission critical environment
with exceptions enabled ( God save the Queen  :D )

Nope, London now, Kings Langley before, and Poland even before that. :) Telecom stuff was elsewhere. In the UK I was working on drivers and firmware for a video decoding IP core. A lot of stories from there as well, it felt like being in the 80's :)
Now I'm gladly not in the industry anymore, just submitted my PhD and now I'm a research engineer at a university (to transfer our research to the industrial sponsor, a lot of freedom, no corporate Dilbert-like scenarios, a lot of prototyping or making quick-and-dirty demos).

BTW on the Google Style Guide I like this review:
https://www.linkedin.com/pulse/20140503193653-3046051-why-google-style-guide-for-c-is-a-deal-breaker
« Last Edit: October 17, 2016, 06:04:34 pm by lukier »
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
template metaprogramming

about the capability of making a generic interfaces
and let the compiler to instantiate things for you
I really like the "generic" method offered by ADA:
generic parameters, instances of generic packages
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
about the capability of making a generic interfaces
and let the compiler to instantiate things for you
I really like the "generic" method offered by ADA:
generic parameters, instances of generic packages

I always wanted to do something in Ada. It has even stronger type safety than C++ (probably because there is no C backward compatibility to maintain), it has generics, exceptions etc. But I never had time to properly learn it and prepare the entire BSP or port RTEMS to my devkits, especially the bare metal MCU ones, not big-ARM devboards.

Even with Ada one can go wrong :)
https://en.wikipedia.org/wiki/Cluster_(spacecraft)
 

Offline IanB

  • Super Contributor
  • ***
  • Posts: 11885
  • Country: us
Kings Langely

Is Kings Langley (interestingly, the spellchecker catches it for me). Clever spellchecker!  :)
 

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
I think that anything with a recent enough version of GCC or LLVM will work. So far I know that there are up-to-date versions of GCC for ARM, AVR and x86 (yes Intel is making microcontrollers based on x86 and amd64 architecture, but so far those are all BGA chips), and LLVM can target ARM and x86.
 

Offline andersm

  • Super Contributor
  • ***
  • Posts: 1198
  • Country: fi
(yes Intel is making microcontrollers based on x86 and amd64 architecture, but so far those are all BGA chips)
The Quark D2000 is (only) available in a QFN package.

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
(yes Intel is making microcontrollers based on x86 and amd64 architecture, but so far those are all BGA chips)
The Quark D2000 is (only) available in a QFN package.

I don't think that core runs AMD64 or x86 though...
 

Offline andersm

  • Super Contributor
  • ***
  • Posts: 1198
  • Country: fi
The Quark D2000 is (only) available in a QFN package.
I don't think that core runs AMD64 or x86 though...
The D2000 uses the P5 ISA (sans floating-point), it's the D1000 that's not x86-compatible.

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
The Quark D2000 is (only) available in a QFN package.
I don't think that core runs AMD64 or x86 though...
The D2000 uses the P5 ISA (sans floating-point), it's the D1000 that's not x86-compatible.
So not exactly either x86 or amd64, but a weird cut-down version of it. I want to know if there is any open-source compiler support for those chips. Those are not cheap either by the way.

If I need a 3.3V MCU at 40 pins with similar features I would prefer STM32F103CB or PIC18F46K20 anyway.
 

Offline andersm

  • Super Contributor
  • ***
  • Posts: 1198
  • Country: fi
I want to know if there is any open-source compiler support for those chips.
GCC should work with the D2000, but I'm not aware of any compiler other than Intel's own supporting the D1000.

EDIT: I would consider those two chips as more of a technology preview/proofs of concept anyway. They're available in exactly one version each, both with pretty anemic flash and memory sizes, and some of the documentation for the D2000 is available only if you're an Intel industry partner. There's also no D1000 board for sale to the general public, even though there's mention of one in the documentation.
« Last Edit: October 16, 2016, 05:14:30 pm by andersm »
 

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
I want to know if there is any open-source compiler support for those chips.
GCC should work with the D2000, but I'm not aware of any compiler other than Intel's own supporting the D1000.

EDIT: I would consider those two chips as more of a technology preview/proofs of concept anyway. They're available in exactly one version each, both with pretty anemic flash and memory sizes, and some of the documentation for the D2000 is available only if you're an Intel industry partner. There's also no D1000 board for sale to the general public, even though there's mention of one in the documentation.
GCC may not be aware of the instructions cut from normal i586 architecture.
 

Offline andersm

  • Super Contributor
  • ***
  • Posts: 1198
  • Country: fi
GCC may not be aware of the instructions cut from normal i586 architecture.
Intel's own System Studio uses GCC. The -msoft-float and -mno-fp-ret-in-387 options should be enough to suppress generation of floating-point instructions, though I assume FPU emulation is also possible.

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
and people can actually live
without blathering -G-C-C-
*in every topic*, ain't it?

long life and prosper  :palm:
 

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
and people can actually live
without blathering -G-C-C-
*in every topic*, ain't it?

long life and prosper  :palm:
So what is your problem with GCC?

GCC and clang/LLVM are probably the two best free (both as in beer and as in speech) compilers out there, and those are also the two compilers that almost always implement the latest language standards and features. There are more companies and government agencies than you can imagine out there that uses and supports those projects.
 

Offline EBRAddict

  • Contributor
  • Posts: 26
  • Country: us
In case nobody pointed this out there are a couple issues that I've found with the Raspberry Pi 3 B GPIO: the UART/serial port doesn't function out of the box because the Bluetooth peripheral took it. To use UART you have to enable a secondary peripheral and slow down the system clock for it to work. Also, the I2C/smbus does not support clock stretching.

BeagleBone Black/Wireless/Green may be a linux alternative (albeit with much smaller community support).

I like the Pi and have several, but when I need GPIO I find myself reaching for an Arduino or a PSoC.

 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
GCC
GCC
GCC

GCC
the best free


it's annoying since a while, dude
it's so f*cking annoying to hear
the same record again, and again
you are making me round like
a record, round round round

what's your problem about life?
money? girls? wife? ….
 
The following users thanked this post: neil555

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
but when I need GPIO I find myself reaching for an Arduino or a PSoC.

yeah, for those things we'd better go for the YUN approach
 

Offline farsi

  • Regular Contributor
  • *
  • Posts: 66
just to add that a list of getting started with embedded unix boards is here: http://embeddednodejs.com/sbc/ - I can confirm that the plug and play experience of the upboard (with ubilinux) was quite good http://www.up-board.org/
 

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
GCC
GCC
GCC

GCC
the best free


it's annoying since a while, dude
it's so f*cking annoying to hear
the same record again, and again
you are making me round like
a record, round round round

what's your problem about life?
money? girls? wife? ….
So what is YOUR problem then? Way too much money or girls? I'd happy to take some if you'd like to share, then maybe I can stop being a cheapskate and start looking into those costly tools you are so fascinated about.

Even for basic C support paid tools like Keil or IAR is lacking. C99 support is just added and if your code calls for C11, well dream on. By the way, even Keil have gave up on their own compiler as there is not going to be any ARMv8-M support in their own compiler, and if you target ARMv8-M in uVision 5 you ended up using clang/LLVM. A modified version, but silll based on the open source LLVM code.
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
dude, the problem is: YOU are so
so f*cking annoying with that
Actually no, you are getting into every thread and bash GCC.
Alex
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Actually no, you are getting into every thread and bash GCC.

oh, really?  in this topic it's happening again:
title "Taking a C++ class, looking for a C++14 compatible microcontroller to play with"
we were talking about *the language itself* (with an interest for some features)
and … oh, see, GCC once again is actually the topic


so, everything, even the hardware MUST be gcc-compilant
because blablablablabla  :blah:

fsck off, last time I waste my time
 

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
Actually no, you are getting into every thread and bash GCC.

oh, really?  in this topic it's happening again:
title "Taking a C++ class, looking for a C++14 compatible microcontroller to play with"
we were talking about *the language itself* (with an interest for some features)
and … oh, see, GCC once again is actually the topic


so, everything, even the hardware MUST be gcc-compilant
because blablablablabla  :blah:

fsck off, last time I waste my time
Point me to one of your favorite compiler on any architecture that is 1) not based on GCC or LLVM/clang, and 2) supports C++14.

If the compiler does not support the language any more talk is BS. And so far the most famous compilers that advertise C++14 support are either GCC, LLVM/clang or a derivative of them. So as of October 2016 talking about C++14 is synonymous with talking about "supported by latest GCC or LLVM/clang"
« Last Edit: October 17, 2016, 07:06:19 pm by technix »
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Actually no, you are getting into every thread and bash GCC.

oh, really?  in this topic it's happening again:
title "Taking a C++ class, looking for a C++14 compatible microcontroller to play with"
we were talking about *the language itself* (with an interest for some features)
and … oh, see, GCC once again is actually the topic


so, everything, even the hardware MUST be gcc-compilant
because blablablablabla  :blah:

fsck off, last time I waste my time

lol, funniest thing I read all day.
 

Offline amyk

  • Super Contributor
  • ***
  • Posts: 8275
The Quark D2000 is (only) available in a QFN package.
I don't think that core runs AMD64 or x86 though...
The D2000 uses the P5 ISA (sans floating-point), it's the D1000 that's not x86-compatible.
It's a 486SX core with some P5 instructions added on. If I remember correctly, many of the diagrams and text in the datasheet were identical to those in the 486 manual, but with the name changed.
 

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
There's also no D1000 board for sale to the general public, even though there's mention of one in the documentation.

It exists, but apparently it's not available to the general public...

http://www.cnx-software.com/2015/11/10/intel-quark-d1000-customer-reference-board-and-intel-system-studio-for-microcontrollers/

The D2000 development kit is available at mouser for $15...

http://www.mouser.com/ProductDetail/Intel/MTFLDCRBDAL/?qs=sGAEpiMZZMvzNxwKcL67%252bpwZleYEABNkLLpgXezJXXQ%3d

« Last Edit: October 18, 2016, 07:23:27 pm by nbritton »
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Historical reasons and Linus' personal animosity towards C++, probably related to the former. When Linux was started C++ wasn't that mature, compilers buggy and the UNIX tradition has always been K&R C.
I've never spoken to Linus, but spent some time trying to guess at this animosity... and he may have a point. One of the problems with a large distributed project like Linux is making sure that lots of folks are able to contribute. C++ as a language could work against that because it *is* a very complicated tool and can be used so many different ways that one programmer's C++ may be almost unrecognizable to another. That's something Linus probably can't afford.

OTOH, a focused team with experienced engineers and the ability to adhere to coding standards can mandate certain restrictions in the C++ they write and do good work. Again, clang and LLVM are a positive example. Google has 100 million lines of C++, so it seems they've found a way to tame the complexity beast too.

Where I work, everything from the reset handler on up is written in C++ 11. All that stuff runs on a Cortex-M0, and is a pleasure to work with.
 
The following users thanked this post: lukier

Offline nbrittonTopic starter

  • Frequent Contributor
  • **
  • Posts: 443
  • Country: us
Historical reasons and Linus' personal animosity towards C++, probably related to the former. When Linux was started C++ wasn't that mature, compilers buggy and the UNIX tradition has always been K&R C.
I've never spoken to Linus, but spent some time trying to guess at this animosity... and he may have a point. One of the problems with a large distributed project like Linux is making sure that lots of folks are able to contribute. C++ as a language could work against that because it *is* a very complicated tool and can be used so many different ways that one programmer's C++ may be almost unrecognizable to another. That's something Linus probably can't afford.

I have spoken to Linus, but I can't speak towards his animosities. However, I would hazard to guess that it's 99% historical reasons. Ken Thompson, Dennis Ritchie, et. al. wrote Unix in C for the PDP. The source code to Unix was then distributed throughout academic circles and this developed into it's own variant of Unix called BSD. Many flocked to this because the source code was open and it had first mover advantage at the time prior to the AT&T lawsuit. Had there not been the lawsuit I'm not sure Linux would even be around, but that's another story. Anyways, universities would teach their CS students about Unix because the source code was accessible, if you had a license. However, Unix grew into a beast so then Minix came along out of the need to simply teaching concepts for students, but I think it cost money etc. Anyways, along comes Linus and if I recall correctly he couldn't afford or was otherwise unable to get a license for Minix, so he said screw it and started banging away on the code for Linux. This was just as the Internet was blossoming, so this good timing combined with the AT&T lawsuit made Linux take off and the rest is history. The majority of the reason it's written in C is simply due to inertia from the original implementation of Unix.

https://en.wikipedia.org/wiki/History_of_Unix#/media/File:Unix_history-simple.svg
« Last Edit: October 20, 2016, 06:38:21 am by nbritton »
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
I've never spoken to Linus, but spent some time trying to guess at this animosity... and he may have a point. One of the problems with a large distributed project like Linux is making sure that lots of folks are able to contribute. C++ as a language could work against that because it *is* a very complicated tool and can be used so many different ways that one programmer's C++ may be almost unrecognizable to another. That's something Linus probably can't afford.

There might be some truth in that, a beginner might use C++ like C, someone on the intermediate level will add classes and then on the advanced level there is template metaprogramming and each of this "styles" looks visually different.

Again, as I said before, every developer should know their tools. Maybe I still have some hope when it comes to people, more than you or Linus, so I don't like the idea of resorting to C as a cure for hypothesized incompetence of the contributors.
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
The majority of the reason it's written in C is simply due to inertia from the original implementation of Unix.

kernels written in pascal or m2 were rejected by developers
probably because of their silly ego-burst attitude

something that (still?) sounds like
- if you are really a man, then your work is written in C,
everything else (Pascal?, Modula2?) is a for bitches and kids,
ADA is obviously only for those who are in the Army
-

I have seen this attitude in person, different times  :-//
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
The source code to Unix was then distributed
throughout academic circles and this developed
into it's own variant of Unix called BSD

along the way, from the academic circles
to big irons, the arise of commercial UNIXs
things like IRIX  :D

the DASH backstage, both hardware
and software side, is also interesting


 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
I've never spoken to Linus, but spent some time trying to guess at this animosity... and he may have a point. One of the problems with a large distributed project like Linux is making sure that lots of folks are able to contribute. C++ as a language could work against that because it *is* a very complicated tool and can be used so many different ways that one programmer's C++ may be almost unrecognizable to another. That's something Linus probably can't afford.

There might be some truth in that, a beginner might use C++ like C, someone on the intermediate level will add classes and then on the advanced level there is template metaprogramming and each of this "styles" looks visually different.

Again, as I said before, every developer should know their tools. Maybe I still have some hope when it comes to people, more than you or Linus, so I don't like the idea of resorting to C as a cure for hypothesized incompetence of the contributors.

Yeah, that's wonderful in theory but, in this case, doesn't work in practice: even the language developers didn't understand what they were specifying until their noses were rubbed in it. What chance have mere application developers got?

I remember watching two indicative cases happen: the discussions over several years at to whether "casting away constness" should be allowed or forbidden, and the unintended power of templates.

The latter is hilarious:
Quote
Historically [template metaprogramming] is something of an accident; it was discovered during the process of standardizing the C++ language that its template system happens to be Turing-complete, i.e., capable in principle of computing anything that is computable. The first concrete demonstration of this was a program written by Erwin Unruh, which computed prime numbers although it did not actually finish compiling: the list of prime numbers was part of an error message generated by the compiler on attempting to compile the code
That's from https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming#History_of_TMP with my emphasis added. The original is at http://www.erwin-unruh.de/primorig.html Note: not designed, but discovered - and that's exactly what happened.

The former merely indicates that the language features are very problematic. If you allow "casting away constness", then you allow the compiler to break invariants specified by the programmer. If you forbid "casting away constness" then you prohibit a significant number of useful optimisations. The choice of safety over performance is irreconcilable in this case; hence the length of the discussions in the C++ committees.

Apart from that, the information in the FQA is directly relevant and should not be ignored. http://yosefk.com/c++fqa/ There are very very few programmers that understand all the pitfalls therein. And that's a big problem with the tool.

There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
a beginner might use C++ like C, someone on the intermediate level will add classes
and then on the advanced level there is template metaprogramming and each of this
"styles" looks visually different.

yes, C++ comes with the feature of being "typed" without the price to pay of being pascal-like,
therefore as "step ahead" (the "++" in the name) it's cool for those who hate the other way,
and you can use C++ to check if your (legacy) C code is good

the C++ verbosity is even better than pedantic warnings in C
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
There are very very few programmers that understand
all the pitfalls therein. And that's a big problem with the tool.

agree, my reason to use just a subset 
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
umm, taking a step back to exceptions,
in C++11, what makes the difference is
the "nothrow" keyword

 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
one of the things I don't like about C++
well, exceptions in C++ are "unchecked"

I mean, if you don't specify which exception can be raised
virtually every function and method can raise an exception

the problem is: which one? don't you know? so, bad things might happen
and if they might happen, give them a probability, and they will!

exceptions are an attempt to recover the system fom a tollerable failure
but with unchecked exceptions the whole system can have a crash
they add a probability of disaster. Not Good  :--

"nothrow" says nothing can be raised. Good  :-+
and we came back into the deterministic way
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
There are very very few programmers that understand
all the pitfalls therein. And that's a big problem with the tool.

agree, my reason to use just a subset

A valid response.

Next you have to determine whether all the libraries use a compatible subset, for whatever definition of "compatible" is relevant for your application. And that's not trivial :(
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
yes, C++ comes with the feature of being "typed"

Not in any reliable form, unfortunately.

The data in memory is untyped. Sure, the variable names in the source code can be typed, but that can - and often is - defeated via casting.

Plus, of course, downcasting is a killer: what's the type of "void *"? Yes Virginia, you can cast aCamel into aHorse.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
one of the things I don't like about C++
well, exceptions in C++ are "unchecked"

I mean, if you don't specify which exception can be raised
virtually every function and method can raise an exception

the problem is: which one? don't you know? so, bad things might happen
and if they might happen, give them a probability, and they will!

exceptions are an attempt to recover the system fom a tollerable failure
but with unchecked exceptions the whole system can have a crash
they add a probability of disaster. Not Good  :--

"nothrow" says nothing can be raised. Good  :-+
and we came back into the deterministic way

Yes.

Curiously in the Java ecosystem there is a move towards unchecked exceptions. The "rationale", and I use that word loosely, is that exceptions are a pain and usually all we can do is abort, so just wrap your code in catchall.

But my opinion is that checked exceptions are a good way to improve a codebase, because they force a function's client to understand the ways in which it might fail and design accordingly. Even if that design is to abort, it is clear what is happening.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
The latter is hilarious:
Quote
Historically [template metaprogramming] is something of an accident; it was discovered during the process of standardizing the C++ language that its template system happens to be Turing-complete, i.e., capable in principle of computing anything that is computable. The first concrete demonstration of this was a program written by Erwin Unruh, which computed prime numbers although it did not actually finish compiling: the list of prime numbers was part of an error message generated by the compiler on attempting to compile the code
That's from https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming#History_of_TMP with my emphasis added. The original is at http://www.erwin-unruh.de/primorig.html Note: not designed, but discovered - and that's exactly what happened.

I've heard that story. On one hand it might be worrying, on the other hand I find it fascinating that something in CompSci can be "discovered". And TMP is a wonderful and rather unique feature (Generics from C# or Java are no match). Of course it can be abused, for example I consider Boost Spirit purely academic exercise, as the compile times and binary sizes are not acceptable. But it doesn't prove TMP useless and someone with less academic bent can do EBNF parser in a more usable and lightweight form, e.g. http://www.gbresearch.com/axe/ which I even once used on STM32F4 to parse G-code.

The former merely indicates that the language features are very problematic. If you allow "casting away constness", then you allow the compiler to break invariants specified by the programmer. If you forbid "casting away constness" then you prohibit a significant number of useful optimisations. The choice of safety over performance is irreconcilable in this case; hence the length of the discussions in the C++ committees.

I think some gaps in type safety and casting away constness actually come from C backwards compatibility. As I said before, I would prefer a rock solid type system from Ada, but I don't use Ada because there are not so many libraries, while in C++ I have awesome C++ libraries (AXE mentioned above, Eigen algebra, Boost/STL etc) and I can use the outcomes of decades of C development (thousands of libraries) if I have to. Pros and cons always.

Apart from that, the information in the FQA is directly relevant and should not be ignored. http://yosefk.com/c++fqa/ There are very very few programmers that understand all the pitfalls therein. And that's a big problem with the tool.

FQA has some valid points, but the author seems really bitter and writes in a manner indicating that C++ is the source of all evil. Other languages have bugs and loopholes too. In C++ I was always perplexed why std::fstream takes const char* for the filename, while STL provides std::string class. Not very consistent. In C for example, think of thousands of security bugs caused by unsafe C standard library functions (for example buffer overflows in gets, scanf, or strtok) and general C attitude encouraging void* and pointer arithmetic (in C++ I always prefer references if I can and containers checking range). I bet there are silly things hiding in C# or Java, but I don't follow these languages much.

Anyway, in any language one should know the limitation, bugs, workarounds and other idiosyncrasies. That's why I don't get the argument that writing Linux in C will lead to better code. Bad C++ programmers will abuse type safety, won't catch exceptions and overdo TMP, bad C programmers will be leaking memory everywhere, creating buffer overflows, because they don't know about e.g. snprintf and invent a horrible meta-language in C preprocessor macros.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
The latter is hilarious:
Quote
Historically [template metaprogramming] is something of an accident; it was discovered during the process of standardizing the C++ language that its template system happens to be Turing-complete, i.e., capable in principle of computing anything that is computable. The first concrete demonstration of this was a program written by Erwin Unruh, which computed prime numbers although it did not actually finish compiling: the list of prime numbers was part of an error message generated by the compiler on attempting to compile the code
That's from https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming#History_of_TMP with my emphasis added. The original is at http://www.erwin-unruh.de/primorig.html Note: not designed, but discovered - and that's exactly what happened.

I've heard that story. On one hand it might be worrying, on the other hand I find it fascinating that something in CompSci can be "discovered". And TMP is a wonderful and rather unique feature (Generics from C# or Java are no match). Of course it can be abused, for example I consider Boost Spirit purely academic exercise, as the compile times and binary sizes are not acceptable. But it doesn't prove TMP useless and someone with less academic bent can do EBNF parser in a more usable and lightweight form, e.g. http://www.gbresearch.com/axe/ which I even once used on STM32F4 to parse G-code.

Agreed, templates are not useless and are more powerful than those in Java/C#. But that wasn't the point I was making.

The key issue is that the language is so baroquely complex that nobody understands it - even the designers. That is the sign of a poor tool.

Quote
The former merely indicates that the language features are very problematic. If you allow "casting away constness", then you allow the compiler to break invariants specified by the programmer. If you forbid "casting away constness" then you prohibit a significant number of useful optimisations. The choice of safety over performance is irreconcilable in this case; hence the length of the discussions in the C++ committees.

I think some gaps in type safety and casting away constness actually come from C backwards compatibility. As I said before, I would prefer a rock solid type system from Ada, but I don't use Ada because there are not so many libraries, while in C++ I have awesome C++ libraries (AXE mentioned above, Eigen algebra, Boost/STL etc) and I can use the outcomes of decades of C development (thousands of libraries) if I have to. Pros and cons always.

I was an early Java adopter 20 years (gulp) ago, and still flip between Java and C as appropriate.

Back then I was pleasantly surprised at how many libraries from many different sources rapidly appeared and all functioned together. That has never happened with C/C++, even now.

Quote
Apart from that, the information in the FQA is directly relevant and should not be ignored. http://yosefk.com/c++fqa/ There are very very few programmers that understand all the pitfalls therein. And that's a big problem with the tool.

FQA has some valid points, but the author seems really bitter and writes in a manner indicating that C++ is the source of all evil. Other languages have bugs and loopholes too. In C++ I was always perplexed why std::fstream takes const char* for the filename, while STL provides std::string class. Not very consistent. In C for example, think of thousands of security bugs caused by unsafe C standard library functions (for example buffer overflows in gets, scanf, or strtok) and general C attitude encouraging void* and pointer arithmetic (in C++ I always prefer references if I can and containers checking range). I bet there are silly things hiding in C# or Java, but I don't follow these languages much.

Anyway, in any language one should know the limitation, bugs, workarounds and other idiosyncrasies. That's why I don't get the argument that writing Linux in C will lead to better code. Bad C++ programmers will abuse type safety, won't catch exceptions and overdo TMP, bad C programmers will be leaking memory everywhere, creating buffer overflows, because they don't know about e.g. snprintf and invent a horrible meta-language in C preprocessor macros.

Yes, but even the designers don't understand all the interactions - let alone mere mortal developers. Hence your wish that programmers should know their tool will never happen with C/C++ can only be a wish; meanwhile back on planet Earth... :)

The FQA isn't the only document to that effect - you can search the usenet archives for the experiences of those that took part in the standardisation committees in the 90s and later. Their experiences, and they know far more than me, made me realise that C/C++ was becoming very problematic. Subsets are less problematic, but they have their own problems.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
to whom is interested in some old stories:

I was an early Java adopter 20 years (gulp) ago,
and still flip between Java and C as appropriate.


2001? do you remember the effort of those
like Dallas Semiconductor (Maxim) had put
in the direction of tini-java/390 platform?

under the cost of 40 UKP, it was famous
in United Kingdom because used in some british
computer science campus whose articles were
about weather stations

how to implement your own, able to be send
and receive remote data from the internet

Java mixed with C/C++, gold ages  :popcorn:
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
to whom is interested in some old stories:

I was an early Java adopter 20 years (gulp) ago,
and still flip between Java and C as appropriate.


2001? do you remember the effort of those
like Dallas Semiconductor (Maxim) had put
in the direction of tini-java/390 platform?

under the cost of 40 UKP, it was famous
in United Kingdom because used in some british
computer science campus whose articles were
about weather stations

how to implement your own, able to be send
and receive remote data from the internet

Java mixed with C/C++, gold ages  :popcorn:

It rings a vague bell, but then I sort-of-vaguely remember many "small Java" platforms.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 


Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch


CppCon 2016: Jason Turner "Rich Code for Tiny Computers: A Simple Commodore 64 Game in C++17" OMG  :-DD :-DD :-DD
 

Offline John Coloccia

  • Super Contributor
  • ***
  • Posts: 1212
  • Country: us

I have spoken to Linus, but I can't speak towards his animosities.

He's written about it, but honestly his arguments don't really hold any water except for the one that goes, "It's too easy for bad programmers to write exceptionally bad C++ code." My words, not his, but sums it up nicely.

I can personally think of a lot of things I don't like about C++. I'm not a huge fan of STL, though it's workable. Could be better. I personally think that multiple inheritance is completely unnecessary and causes way more trouble than it's worth. The interface model is better. Exception handling is cute, though it often gets used as a somewhat safe goto instead of an exception handler. Heavens, I can go on and on. It takes a bit of maturity to use C++ properly and I personally would not want to lead a project with a bunch of volunteers hacking away at C++.

But as a professional tool with competent people in charge? It's really quite good and powerful, and simplifies things enormously.
« Last Edit: October 24, 2016, 02:25:03 am by John Coloccia »
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
CppCon 2016: Jason Turner "Rich Code for Tiny Computers: A Simple Commodore 64 Game in C++17" OMG  :-DD :-DD :-DD

Very nice talk, demonstrating live how nice the output assembly can be with compile time constructs, TMP, inlining and other C++ features, all without loosing the clarity of the original source (think how readable and testable it would be if peppered with inline assembly or if done as a one huge C function with macros). And it would only get better with proper compiler backend for a particular architecture. I think this proves that C++ is perfectly fine for embedded, one cannot get more embedded nowadays than 6502 :)
 

Offline timb

  • Super Contributor
  • ***
  • Posts: 2536
  • Country: us
  • Pretentiously Posting Polysyllabic Prose
    • timb.us


CppCon 2016: Jason Turner "Rich Code for Tiny Computers: A Simple Commodore 64 Game in C++17" OMG  :-DD :-DD :-DD

Holy shit, that was kind of amazing! Who would have thought to compile for i386 and then run the result through an x86 to 6502 reassembler... Thanks for posting that!
Any sufficiently advanced technology is indistinguishable from magic; e.g., Cheez Whiz, Hot Dogs and RF.
 

Offline Bruce Abbott

  • Frequent Contributor
  • **
  • Posts: 627
  • Country: nz
    • Bruce Abbott's R/C Models and Electronics
demonstrating live how nice the output assembly can be with compile time constructs, TMP, inlining and other C++ features, all without loosing the clarity of the original source (think how readable and testable it would be if peppered with inline assembly
The 'clarity of the original source'?

Explain how

Code: [Select]
*reinterpret_cast<uint8_t*>(53280) = 1;
is clearer than

Code: [Select]
lda  #1
sta  53280
 
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
Code: [Select]
*reinterpret_cast<uint8_t*>(53280) = 1;

I'd rather watch the entire talk before posting.

is clearer than
Code: [Select]
lda  #1
sta  53280

I won't feed the troll. I'll say that for some reason we have moved from assembly to high level languages in the 1960's. Maybe not everyone got the news.
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
we have moved from assembly
to high level languages in the 1960's.
Maybe not everyone got the news.

well, I would say 1990's
considering that
AmigaOS/classic and RiscOS/classic
were both written in assembly

and personally I am back to assembly
yes, right now, 2016 :D




(does it sound like "back to the future"
like the movie?  :popcorn: )


« Last Edit: October 23, 2016, 10:00:33 pm by legacy »
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
I think this proves that C++ is perfectly
fine for embedded, one cannot get more
embedded nowadays than 6502 :)

yes, I am considering to move into C++14
therefore I am open to this kind of *talk*

 :-+
 

Offline lukier

  • Supporter
  • ****
  • Posts: 634
  • Country: pl
    • Homepage
I have nothing against assembly as such, sometimes some inline might be required (e.g. inline for SSE/AVX accelerations), but no one in a sane mind would write any project of sensible complexity in assembly, not in 2016. I often prefer to inspect the output assembly to see if I could hint the compiler to do better instead of writing inline snippets.

Maybe the advantages of the example presented in the talk are not clear to everyone. Let me explain. His memory(...) function with this reinterpret_cast is the only contact point with the hardware. One might call it a minimalistic HAL. The rest is C++ business as usual, readable to anyone familiar with C++ and not necessarily this particular chip assembly language.

Also, this is very easy to test. This memory(...) function can be mocked and unit tests can be written in C++ and run on developer's workstation (as there is no inline assembly!) and Continuous Integration systems. In the next step this function might instead interface with SystemC simulation of 6502 or a Cadence simulator - sometimes the hardware is not there yet. Only when hardware reaches FPGA and ASIC levels we can actually run the vanilla code somewhere, and this can be expensive so such testing is done in the later stages and mostly for performance profiling.

Additionally, this memory(...) function can be, for some test build type, replaced with a function that does RPC over UART/Ethernet/whatever to the target system running only so called "Monitor" that only reads and writes to memory/peripherals, while the code itself runs on x86.

Of course all this testing can be done with C and has been, but may require more ugly constructs (preprocessor macros etc), and with inline assembly it becomes a royal pain. The point here is that it might seem that his game is very abstracted (and this improves testability), with classes, TMP and other C++ tricks, and yet it produces very neat and compact assembly.
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4199
  • Country: us
Apparently "Embedded C++" is so far from "Real C++" that C++ programmers will sneer at you...
http://softwareengineering.stackexchange.com/questions/48401/learning-c-properly-not-c-with-classes
(especially: "you should definitely be using all of those self-expanding containers from the STL.")

(is there an "embedded STL" that omits dynamic allocation?  That might be interesting...)
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4199
  • Country: us
Quote
Explain how
*reinterpret_cast<uint8_t*>(53280) = 1;
is clearer than
lda  #1

sta  53280
Hopefully your actual program ends up containing something like:
Code: [Select]
   TIMER1_ENA = 1;or
Code: [Select]
   lda #1
   sta TIMER1_ENA
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Code: [Select]
#include <functional>
#include <type_traits>

template<typename BASE>
constexpr bool _isOneOf_f()
{
    return false;
}

template<typename BASE, typename TEST, typename... TYPES>
constexpr bool _isOneOf_f()
{
    return std::is_same<BASE, TEST>::value || _isOneOf_f<BASE, TYPES...>();
}

template<typename BASE, typename... TYPES>
constexpr bool isOneOf = _isOneOf_f<BASE, TYPES...>();


template<typename V1>
constexpr auto _biggestValue_f(const V1 v1)
{
    return v1;
}

template<typename V1, typename... TYPES>
constexpr auto _biggestValue_f(const V1 v1, const TYPES... others)
{
    return std::max(v1, _biggestValue_f(others...));
}

template<typename... TYPES>
constexpr auto biggestTypeSize = _biggestValue_f(sizeof(TYPES)...);



template<typename TOSEARCH>
constexpr int _findTypeIndex_f(const int indexSoFar)
{
    return -1;
}

template<typename TOSEARCH, typename TEST, typename... TYPES>
constexpr int _findTypeIndex_f(const int indexSoFar)
{
    if(std::is_same<TOSEARCH, TEST>::value)
        return indexSoFar;
    else
        return _findTypeIndex_f<TOSEARCH, TYPES...>(indexSoFar + 1);
}

template<typename TOSEARCH, typename... TYPES>
constexpr int findTypeIndex = _findTypeIndex_f<TOSEARCH, TYPES...>(0);



template<typename RETTYPE, typename... ERRORTYPES>
class Except
{
    private:
        char values[biggestTypeSize<RETTYPE, ERRORTYPES...>];
        int whichIsIt = 0;


    public:

        template<
            typename TYPE,
            typename = std::enable_if_t< isOneOf<TYPE, RETTYPE, ERRORTYPES...> >
        >
        Except(TYPE value)
            : whichIsIt{ findTypeIndex<TYPE, RETTYPE, ERRORTYPES...> }
        {
            TYPE *ptr = reinterpret_cast<TYPE*>(&this->values[0]);
            *ptr = value;
        }


        template<
            typename ERRT,
            typename = std::enable_if_t< isOneOf<ERRT, ERRORTYPES...> >
        >
        Except<RETTYPE, ERRORTYPES...> & when(const std::function<void(const ERRT &)> & callback)
        {
            if(findTypeIndex<ERRT, RETTYPE, ERRORTYPES...> == whichIsIt)
                callback(*reinterpret_cast<ERRT*>(&this->values[0]));
            return *this;
        }


        void ok(const std::function<void(const RETTYPE &)> & callback)
        {
            if(whichIsIt == 0)
                callback(*reinterpret_cast<RETTYPE*>(&this->values[0]));
        }
};


above the attempt of handing exceptions-like
with "exceptions disabled" flag, which sounds
like impossible mission, and the arrangement
of words & phrases in C++11 seems designed
to cause headache  :palm: :palm: :palm: :palm:

 

Offline John Coloccia

  • Super Contributor
  • ***
  • Posts: 1212
  • Country: us
Code: [Select]
#include <functional>
#include <type_traits>

template<typename BASE>
constexpr bool _isOneOf_f()
{
    return false;
}

template<typename BASE, typename TEST, typename... TYPES>
constexpr bool _isOneOf_f()
{
    return std::is_same<BASE, TEST>::value || _isOneOf_f<BASE, TYPES...>();
}

template<typename BASE, typename... TYPES>
constexpr bool isOneOf = _isOneOf_f<BASE, TYPES...>();


template<typename V1>
constexpr auto _biggestValue_f(const V1 v1)
{
    return v1;
}

template<typename V1, typename... TYPES>
constexpr auto _biggestValue_f(const V1 v1, const TYPES... others)
{
    return std::max(v1, _biggestValue_f(others...));
}

template<typename... TYPES>
constexpr auto biggestTypeSize = _biggestValue_f(sizeof(TYPES)...);



template<typename TOSEARCH>
constexpr int _findTypeIndex_f(const int indexSoFar)
{
    return -1;
}

template<typename TOSEARCH, typename TEST, typename... TYPES>
constexpr int _findTypeIndex_f(const int indexSoFar)
{
    if(std::is_same<TOSEARCH, TEST>::value)
        return indexSoFar;
    else
        return _findTypeIndex_f<TOSEARCH, TYPES...>(indexSoFar + 1);
}

template<typename TOSEARCH, typename... TYPES>
constexpr int findTypeIndex = _findTypeIndex_f<TOSEARCH, TYPES...>(0);



template<typename RETTYPE, typename... ERRORTYPES>
class Except
{
    private:
        char values[biggestTypeSize<RETTYPE, ERRORTYPES...>];
        int whichIsIt = 0;


    public:

        template<
            typename TYPE,
            typename = std::enable_if_t< isOneOf<TYPE, RETTYPE, ERRORTYPES...> >
        >
        Except(TYPE value)
            : whichIsIt{ findTypeIndex<TYPE, RETTYPE, ERRORTYPES...> }
        {
            TYPE *ptr = reinterpret_cast<TYPE*>(&this->values[0]);
            *ptr = value;
        }


        template<
            typename ERRT,
            typename = std::enable_if_t< isOneOf<ERRT, ERRORTYPES...> >
        >
        Except<RETTYPE, ERRORTYPES...> & when(const std::function<void(const ERRT &)> & callback)
        {
            if(findTypeIndex<ERRT, RETTYPE, ERRORTYPES...> == whichIsIt)
                callback(*reinterpret_cast<ERRT*>(&this->values[0]));
            return *this;
        }


        void ok(const std::function<void(const RETTYPE &)> & callback)
        {
            if(whichIsIt == 0)
                callback(*reinterpret_cast<RETTYPE*>(&this->values[0]));
        }
};


above the attempt of handing exceptions-like
with "exceptions disabled" flag, which sounds
like impossible mission, and the arrangement
of words & phrases in C++11 seems designed
to cause headache  :palm: :palm: :palm: :palm:

It that from a new STL? Like I said before, I'm not a huge fan of the STL, though it's not particularly terrible for what it does. It's just a little bloated.

Anyhow, I'm not sure I really like C++11 either. I think it's trying to do too much. I like C++ as an object oriented extension to C, along with being a more strongly typed language. I like it for embedded and system level programming. IMHO, it misses the mark as a modern language. That's not to say you need a modern language, and C++ is just fine for quite a few things, but trying to turn it into a modern language just doesn't feel like it's working. The syntax and rules just get more and more complex and obfuscated. It's not insurmountable, but I feel like it's counterproductive.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Anyhow, I'm not sure I really like C++11 either. I think it's trying to do too much. I like C++ as an object oriented extension to C, along with being a more strongly typed language. I like it for embedded and system level programming. IMHO, it misses the mark as a modern language. That's not to say you need a modern language, and C++ is just fine for quite a few things, but trying to turn it into a modern language just doesn't feel like it's working. The syntax and rules just get more and more complex and obfuscated. It's not insurmountable, but I feel like it's counterproductive.

Yes indeed.

C++ tries to be both simple and close to the hardware, and also a high-level language - and fails at both. The give-away is how much you can't guarantee, because it is left as "implementation defined".
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
Anyhow, I'm not sure I really like C++11 either. I think it's trying to do too much. I like C++ as an object oriented extension to C, along with being a more strongly typed language. I like it for embedded and system level programming. IMHO, it misses the mark as a modern language. That's not to say you need a modern language, and C++ is just fine for quite a few things, but trying to turn it into a modern language just doesn't feel like it's working. The syntax and rules just get more and more complex and obfuscated. It's not insurmountable, but I feel like it's counterproductive.

Yes indeed.

C++ tries to be both simple and close to the hardware, and also a high-level language - and fails at both. The give-away is how much you can't guarantee, because it is left as "implementation defined".

That is why there is no unified C++11, rather than separate clang++11 or gnu++11 or msvc++11 or icc++11... (clang++11 and gnu++11 are fairly similar though, as clang try to be a drop-in replacement of GCC)
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19503
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Anyhow, I'm not sure I really like C++11 either. I think it's trying to do too much. I like C++ as an object oriented extension to C, along with being a more strongly typed language. I like it for embedded and system level programming. IMHO, it misses the mark as a modern language. That's not to say you need a modern language, and C++ is just fine for quite a few things, but trying to turn it into a modern language just doesn't feel like it's working. The syntax and rules just get more and more complex and obfuscated. It's not insurmountable, but I feel like it's counterproductive.

Yes indeed.

C++ tries to be both simple and close to the hardware, and also a high-level language - and fails at both. The give-away is how much you can't guarantee, because it is left as "implementation defined".

That is why there is no unified C++11, rather than separate clang++11 or gnu++11 or msvc++11 or icc++11... (clang++11 and gnu++11 are fairly similar though, as clang try to be a drop-in replacement of GCC)

Plus why the behaviour of compiled code can (and does) change when the compiler version changes, and why the concept of a portable library is problematic.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Code: [Select]
std::mutex myMutex;


{
   std::lock_guard<std::mutex> guard(myMutex);

   //critical code
...
}
// lock_guard automatically unlocks the mutex


in my spare time I am designing my own language
actually it looks like "--C", but I am grabbing some
interesting feature from C++11, and I like "scopes"


I just need to (re)invent the wheel with a better
syntax  :-DD :-DD :-DD
 

Offline technix

  • Super Contributor
  • ***
  • Posts: 3507
  • Country: cn
  • From Shanghai With Love
    • My Untitled Blog
Code: [Select]
std::mutex myMutex;


{
   std::lock_guard<std::mutex> guard(myMutex);

   //critical code
...
}
// lock_guard automatically unlocks the mutex


in my spare time I am designing my own language
actually it looks like "--C", but I am grabbing some
interesting feature from C++11, and I like "scopes"


I just need to (re)invent the wheel with a better
syntax  :-DD :-DD :-DD

This is from Objective-C:
Code: [Select]
@synchronized (mutex_object)
{
    // ...
    [mutex_object canStillBeUsed:NORMALLY];
    // ...
}

The mutex_object can be any object, not just mutexes.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf