"hello world" demos & templates for various languages, incl. gcc
build commands for C & C++
See also my eRCaGuy_hello_world_data project.
By Gabriel Staples
www.ElectricRCAircraftGuy.com
- Disclaimer: any content herein is my own or otherwise has proper notice of licensing and attribution. This repo contains my own beliefs, opinions, words and works. They are not endorsed by any of my past nor present employers.
- My eRCaGuy_dotfiles repo.
- Learn X in Y minutes: for most-excellent software tutorials written in code in the language itself which you are learning!
- Main Website: https://learnxinyminutes.com/
- GitHub: https://github.com/adambard/learnxinyminutes-docs
- Example tutorials:
- Ones I'd like to study next are marked with a star: ⭐. Ones I have fully studied are marked with a check (none so far): ✅.
- Languages:
- Tools [I know I know!...I consider some of these programming languages too!--like
bash
andawk
]:- Bash - https://learnxinyminutes.com/docs/bash/
- awk - https://learnxinyminutes.com/docs/awk/
- cmake⭐ - https://learnxinyminutes.com/docs/cmake/
- ansible - https://learnxinyminutes.com/docs/ansible/
- git - https://learnxinyminutes.com/docs/git/
- make⭐ - https://learnxinyminutes.com/docs/make/
- linker scripts (Russian only--use Google Translate) - https://learnxinyminutes.com/docs/linker/
- vim - https://learnxinyminutes.com/docs/vim/
(click to expand)
- Status:
- Description: for beginners and experts alike!--not your average "hello world" examples
- How to clone this repo and all git submodules and git lfs files (including tracked binary files, such as PDFs)
1. To clone this repo plus all sub-repos (git submodules) and all
git lfs
Large File Storage files 1. To update this repo as a user of it, to match it exactly as I have made it as the developer of it - A Few Folder & File Notes
- Examples of more advanced principles taught herein:
- File Structure:
- Changelog
- Many solid C & C++ demos are done and work!
- A Python demo also is in place to show how to parse a YAML file.
- bash/argument_parsing__3_advanced__gen_prog_template.sh is a really good advanced bash demo of a full program with advanced features, help menu, full argument parsing, etc. See the bash section below.
See the tree
output below to see the file/folder structure.
Note that these are NOT just your standard "simple" hello world demos for absolute beginners. Rather, they are simple enough for beginners but also contain some advanced techniques and tips & tricks to act as good reminders or teaching for more expert programmers too. I, myself, regularly reference my own examples here to remind myself of some of these details which are easy to forget. There's no sense stressing about trying to remember everything. Instead of trying to remember everything, just remember where to look (here in this case).
How to clone this repo and all git submodules and git lfs files (including tracked binary files, such as PDFs)
This repo contains Git Submodules, which simply means that this is a git repo which contains other git repos. It also uses git lfs
(Large File Storage) to more-efficiently store certain binary files, such as PDFs.
- For details on how to use
git submodule
andgit lfs
, see my notes in my eRCaGuy_dotfiles repo here: how-to-clone-whole-repo. - See also the
= git submodules: =
section of my "git & Linux cmds doc" notes in my eRCaGuy_dotfiles repo here: eRCaGuy_dotfiles/git & Linux cmds, help, tips & tricks - Gabriel.txt.
In short:
# Clone this repo
git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world.git
# Pull all Git LFS files (large binary files, such as PDFs, tracked with `git lfs`)
git lfs pull
# Recursively clone and update all subrepos (git submodules) it may contain
git submodule update --init --recursive
git pull
git lfs pull
git submodule update --init --recursive
- You can add this as an Eclipse project--for source code navigation only, NOT for building! The Eclipse project files/folders are:
.cproject
file.project
file.settings
dir
.clang-format
is the format definition file for auto-formatting C and C++ files withclang-format
.- For full installation and usage instructions for
clang-format
, see the readme in my other repo here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_CodeFormatter. - Quick usage example:
# Format this file in-place (`-i`) clang-format --verbose -i --style=file "path/to/file.c"
- See the other repo here (https://github.com/ElectricRCAircraftGuy/eRCaGuy_CodeFormatter#usage) for more info on what
--style=file
means and how you can place the.clang-format
configuration file at different levels.
- For full installation and usage instructions for
- How to generate intermediate build files, including .ii, .s, and .o.
- How to make a single file compile in both C and C++ by using the
#ifdef __cplusplus
extern "C" {
brace trick- See "c/hello_world.c"
- Note: there is also such a thing as
extern "C++"
. Search the GNU gcc documentation here for that search string: https://gcc.gnu.org/onlinedocs/gcc.pdf. Ex: the top of p489, under the paragraph titled "Language-linkage module attachment", mentions(extern "C" or extern "C++")
.
- How to use a forward declaration of
printf
rather than includingstdio.h
to make it link - How to do cross-platform sleep in Windows or Linux
- A reminder to use
-Wall -Werror
for better code safety and quality - How to use
g3
for full debugging info - How to specify the C or C++ version you are compiling for, such as
c90
,c99
, orc11
(C 2011), orc++98
,c++03
(C++ 2003), orc++11
(C++ 2011) - How to pass entire functions or curly-brace-scoped
{ }
code blocks, as though they were a single parameter, into a macro to be evaluated - How to do integer rounding UP, DOWN, and to NEAREST whole integer during division using 3 different techniques: 1) macros, 2) gcc/clang statement expressions, and 3) C++ function templates. This also is a great unit test example using simple hand-written unit tests.
- See "c/rounding_integer_division/" directory
- If you'd like to see how to use googletest (gtest) and googlemock (gmock) instead of writing custom unit tests, see my other project here instead: https://github.com/ElectricRCAircraftGuy/eRCaGuy_gtest_practice. It also acts as a good demo of how to get up and running quickly with Google's Bazel build system.
- Witness that the C++
std::unordered_map<T_key, T_value>
unordered map (hash table) class automatically implicitly creates a new key/value pair each time you attempt to read OR write to a value (or any members of a complex value, such as astruct
orclass
) which belongs to a non-existing key! In other words, reading or writing any key/value which does NOT yet exists causesstd::unordered_map<>
to automatically, dynamically, generate it right on the spot for you to access it! This is confusing behavior at first, as it happens implicitly behind the scenes, so it needs to be understood. Once understood, it is a powerful feature to use, but a one or two-line comment to exlain that you intend dynamic allocation to happen, above any lines in production code where you use this, would be wise. - Case-insensitive
strncmp()
function, with unit tests.- See "c/strncmpci.c"
- Example of how to manually write unit tests.
- See "c/strncmpci.c"
- Note: for Google Test (gtest/gmock) examples, including how to use the Bazel build system, see my repo here instead: https://github.com/ElectricRCAircraftGuy/eRCaGuy_gtest_practice.
- Example of how to use ANSI color codes (ex: red and green) in terminal output.
- It is possible to colorize and stylize/format your text you print to
stdout
orstderr
, in any programming language, by surrounding the text with special ANSI color codes. This works for all programming languages and all forms of printing tostdout
orstderr
, whether viaprintf("some text\n");
in C or C++,std::cout << "some text\n";
in C++,print("some text")
in Python,echo "some text"
in bash, etc. - See these defines in C in "c/strncmpci.c":
...and how I used them to colorize text in
#define ANSI_COLOR_OFF "\033[m" #define ANSI_COLOR_GRN "\033[32m" #define ANSI_COLOR_RED "\033[31m"
printf()
calls there. - See also my other repo here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/useful_scripts/git-diffn.sh#L126
- It is possible to colorize and stylize/format your text you print to
- How to use a
const
reference to a vector, with a default parameter, as an input param to a function! - How to call command-line system calls in C and C++, read piped input from
stdin
, and read command-line output from called process from itsstdout
:- c/system_call_list_files.c: basic example to call
ls -l
in C, but not read back the output. Rather, it just prints to stdout instead. - See also:
- StackOverflow.com: how to read from stdout in C
- StackOverflow.com: C: Run a System Command and Get Output?
- StackOverflow.com: How can I run an external program from C and parse its output?
- StackOverflow.com: Capturing stdout from a system() command optimally
- [the most-thorough C++ answer I think] StackOverflow.com: How do I execute a command and get the output of the command within C++ using POSIX?
- c/system_call_list_files.c: basic example to call
- Advanced bit-masks and bit-shifting.
- See "cpp/process_10_bit_video_data.cpp"
- See also the problem statement and my answer, with other references, on Stack Overflow here: Stack Overflow: Add bit padding (bit shifting?) to 10bit values stored in a byte array.
- Weak functions (functions with attribute
weak
): prove to myself that weak functions which are declared but not defined really do have addresses equal to nil (ie: zero, or0
), as this is how the ArduinoserialEvent()
function works and is implemented.- See "cpp/check_addr_of_weak_undefined_funcs.cpp".
- See also my Stack Overflow answer here: Arduino “SerialEvent” example code doesn't work on my Arduino Nano. I can't receive serial data. Why?.
- gcc
weak
function attribute: https://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Function-Attributes.htmlweak
The
weak
attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.
- Empirically measure the max thread stack size permitted on your architecture, in C OR C++. See:
- Practice using
void *
function arguments to pass in ANY data type, such as a regularuint32_t
, to a function.void *
is also the required input parameterarg
type, passed bypthread_create()
to thestart_routine
function, so thatarg
can be ANY type! This allows the Linuxpthread_create()
function to be a generic function prototype which allows generic callback functions, to be called by the thread, and which shall receive generic input parameters. GOING FURTHER: The cool thing about this is that avoid *
input parameter can literally be A POINTER TO ANY DATA TYPE, so it could even be to a struct containing more function pointers, or a struct containing a bunch of parameters, etc. In this way, a generic function prototype containing a singlevoid *
input param can actually "wrap", or contain, a ton of input params. There are no limits to what you can pass with this--it's all up to your imagination and ingenuity and desires.- My example usage of this, passing a simple
uint32_t
type via avoid *
input parameter: c/onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c - See also my answer on Stack Overflow here: Stack Overflow: C/C++ maximum stack size of program
- My example usage of this, passing a simple
- Learn 3 techniques to read individual bytes out of variables of any type in gcc C and C++.
- You can use 1) unions and "type punning", 2) raw pointers, or 3) bit-masks and bit shifting!
- See "c/type_punning.c"
- See also my detailed answer and explanations here: Stack Overflow: Portability of using union for conversion - my answer: "Using Unions for "type punning" is fine in C, and fine in gcc's C++ as well (as a gcc [g++] extension). But, "type punning" via unions has hardware architecture endianness considerations.".
- More of my answers:
- (Multidimensional arrays) 2D array practice in C and C++.
- See c/2d_array_practice.c; it runs in both C and C++; see build commands in the comments at the top
- See my full answer on this on Stack Overflow here: How to pass a multidimensional array to a function in C and C++
- See c/2d_array_practice.c; it runs in both C and C++; see build commands in the comments at the top
- Asserts in C:
- c/assert_practice.c - practice using the
assert()
andstatic_assert()
macro wrappers in C11, as well as a customASSERT_TRUE()
macro I wrote which also prints the filename, function name, and line number using built-in macros__FILE__
and__LINE__
, and the special built-in static C-string (char array) variable__func__
.
- c/assert_practice.c - practice using the
- Pre-main() and post-main() function call injection:
- [VERY interesting and neat concept!] Dynamically inject function calls before and after another executable's
main()
function.- AKA: program "constructors" and "destructors" in C.
- AKA: how to use gcc function attributes
constructor
anddestructor
, and C functionatexit()
.
- See c/dynamic_func_call_before_and_after_main.c.
- [VERY interesting and neat concept!] Dynamically inject function calls before and after another executable's
- Dynamic library (shared object
lib*.so
) creation and use, including with the LinuxLD_PRELOAD
preloader trick at call time. - How to use
std::initializer_list<>
as an input arg to a function, likestd::max()
does, so you can easily pass in a variable number of input arguments inside curly braces in order to perform operations on them. In this case, I concatenate any number of input argument strings with/
chars between them in order to build a file path from multiple directory names and the filename at the end.- See cpp/make_path_to_file.cpp
- Sample usage:
// output: `"/dir1/dir2/dir3"` std::string file_path = make_path({"/dir1", "dir2", "dir3"});
- Sample usage:
- See cpp/make_path_to_file.cpp
- Demonstrate how to "remove an element" from an array in C. You might also call this "filtering an array" in C.
- See: c/array_filter_and_remove_element.c. I demonstrate 2 approaches:
- [better] copy the array into a new array (the clean and easy approach), but takes 2x array memory
- filter the array in-pace (the hard and copy-intensive approach), but takes no extra array memory
- See also my answer on this here: Stack Overflow: Removing elements from array in C.
- See: c/array_filter_and_remove_element.c. I demonstrate 2 approaches:
- Demonstrate prefix (
++i
and--i
) vs postfix (i--
andi++
) operators and how they differ.- See: c/preincrement_and_postincrement_demo.c
- In short:
++i
increments the value first, and THEN reads the value.i++
reads the value first, and THEN increments it!
- The same order goes for prefix and postfix decrements (
--i
, andi--
, respectively). - That's it!
- c/system_call_python.c - this program is pretty cool! It has C write and call a Python program using
system()
calls.- In short, it's a C program which uses system calls to write and call a Python script which then uses a system call to ping. Pretty neat. I posted the code also in my answer here: https://stackoverflow.com/a/70285228/4561887.
- Iterate over C
enum
and C++enum class
: Stack Overflow: How can I iterate over an enum? - 4 ways to do function pointers in C++ (2 of which work also in C) - cpp/function_ptr_typedef_vs_std_function.cpp
- Libcurl usage (
#include <curl/curl.h>
) and advanced error handling--ex:enum class Error_code
,struct Error
,return Error::Ok()
, etc.- See the
cpp/curl_lib*
.h
,.cpp
, andunittest.cpp
files.
- See the
-
Use
-Wwarning-name
to turn ON build warning "warning-name", and-Wno-warning-name
to turn OFF build warning "warning-name".-W
turns a warning ON, and-Wno-
turns a warning OFF. Here's what gcc has to say about it (source: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html; emphasis added):You can request many specific warnings with options beginning with
-W
, for example-Wimplicit
to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning-Wno-
to turn off warnings; for example,-Wno-implicit
. This manual lists only one of the two forms, whichever is not the default. -
Instead of
-g3
, use-ggdb
to build debug information specifically for the GNU gdb debugger. If using the clang (LLVM) compiler instead of gcc, you may also use-glldb
to build debug information specifically for the clang LLDB debugger. Note that if you use-glldb
, it usually builds debug symbols and information which works just fine with gdb too, so you can generally use either debugger with the same built symbols in that case. -
Use
-Wall -Wextra -Werror
(which is a good idea) to see all warnings and to convert all warnings to errors, to make you write better code. Some people may leave off-Wextra
, and just use-Wall -Werror
. Others may also like to add-Wpedantic
to that list (now it's-Wall -Wextra -Wpedantic -Werror
) to enforce ISO C and ISO C++ standards, but other people or code-bases will explicitly turn OFF pedantic with-Wno-pedantic
to explicitly DISABLE pedantic (ISO standards) checks and ALLOW compiler extensions. Personally, I prefer to leave compiler extensions ENABLED (meaning: do NOT use-Wpedantic
), as compiler extensions are very frequently used and very useful, especially in small, embedded, low-level and hardware-centric systems such as microcontrollers.- In other words, I recommend that you DO use
-Wall -Wextra -Werror
but that you NOT use-Wpedantic
, but if you'd like to use-Wpedantic
as well, you may. See just below for additional details. - For details on which warning flags
-Wall
and-Wextra
each turn on, refer to the gcc user manual here (https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html), and search the page for these warnings, or just scroll partway down. There's a nice list detailing what individual warning flags are under each (-Wall
, and-Wextra
).
- In other words, I recommend that you DO use
-
Add the
-Wpedantic
or-pedantic
(same thing) build flag to enforce strict ISO C or ISO C++ standards and "reject all programs that use forbidden extensions". Or, conversely, add-Wno-pedantic
to ENABLE extensions and turn a previously-set-Wpedantic
back OFF.-Wpedantic
NOT being on is the default. See gcc's user manual section on Warning Options, for example, as well as the bullet just above, for details: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html.- Some people want strict ISO C and C++ functionality only. They use
-Wpedantic
. - Some libraries REQUIRE compiler extensions and explicitly have
-Wno-pedantic
set for the library to enable compiler extensions and disable any previously-set-Wpedantic
flags. Sometimes this is just for certain files which require exceptions to use certain compiler extensions. - Others rely on compiler extensions and do NOT use
-Wpedantic
. I am in this latter category and prefer NOT to use-Wpedantic
, so that I CAN use gcc (or clang) compiler extensions. They are good. They are safe. They are helpful. They just may not be quite as portable across compilers is all, though from gcc to clang and back again, you are usually ok to use them, since clang strives to be gcc-compatible by design (see http://clang.llvm.org/: clang strives to be gcc compatible: "End-User Features" they advertise include: "GCC compatibility"). - See also my notes about
-Wpedantic
in the previous higher-level bullet just above this one.
- Some people want strict ISO C and C++ functionality only. They use
-
clang, but NOT gcc, also has a
-Weverything
option which appears to include things such as-Wpedantic
. You can test it here: https://godbolt.org/z/qcYKd1. Notice the-Wvla-extension
warning we get since we are relying on a C99 extension in C++ in this case, and we have-Weverything
set. We get the same warning if we just use-Wpedantic
, as shown here: https://godbolt.org/z/M9ahE4, indicating that-Weverything
does in fact include-Wpedantic
. We get no warning if we have neither of those flags set: https://godbolt.org/z/j8sfsY.Despite-Weverything
existing and working in clang, however, I can find no documentation whatsoever on its existence, neither in the clang man pages nor in the online manual here: https://clang.llvm.org/docs/DiagnosticsReference.html.- Note there is also a clang (at least) option for
-Wc99-extensions
to allow them, or-Wno-c99-extensions
to disallow them. Source: https://clang.llvm.org/docs/DiagnosticsReference.html#wc99-extensions. - UPDATE: the bottom of the main clang documentation index page: https://clang.llvm.org/docs/index.html, under the "Indices and tables" section at the very bottom, has a "Search Page" link. Using that link, here is my search for "-Weverything": https://clang.llvm.org/docs/search.html?q=-Weverything, which brings me to the official documentation here!: https://clang.llvm.org/docs/UsersManual.html?highlight=weverything#cmdoption-weverything. Done! There it is!
-
See my answer here: https://stackoverflow.com/questions/64147706/what-does-the-clang-compilers-weverything-option-include-and-where-is-it-doc/64147755#64147755. Clang does NOT recommend using
-Weverything
! They say it's better to use just-Wall -Wextra
instead. See their quote here (emphasis added):Since
-Weverything
enables every diagnostic, we generally don’t recommend using it.-Wall -Wextra
are a better choice for most projects. Using-Weverything
means that updating your compiler is more difficult because you’re exposed to experimental diagnostics which might be of lower quality than the default ones. If you do use-Weverything
then we advise that you address all new compiler diagnostics as they get added to Clang, either by fixing everything they find or explicitly disabling that diagnostic with its correspondingWno-
option.
-
- Note there is also a clang (at least) option for
-
If you include the C math library with
#include <math.h>
, you must add-lm
to the very end of your gcc build command to link to the math library! Technically, you only need-lm
after any .o object file or .c source file which needs it, but it's a good idea to just put all libraries to link against at the very end of the gcc build command.- So, do this:
# DO THIS (has `-lm` at end): # Note: add the math lib last via `-lm` so that any object file or source file before # this point which includes <math.h> will link properly against that library's symbols. gcc -Wall -Wextra -Werror -O3 -std=c17 hello_world_extra_basic.c -o bin/a -lm && bin/a
- NOT this:
# NOT THIS (is missing `-lm`): gcc -Wall -Wextra -Werror -O3 -std=c17 hello_world_extra_basic.c -o bin/a && bin/a
- See:
- This answer: Undefined reference to
sin
- This comment discussion and links between @paxdiablo and myself from this point down.
- In short, you technically only need to link to a library
my_library
with-lmy_library
directly after any .o object file or .c source file which needs it, but practically (meaning: it's a good, practical, rule of thumb to do so) you should just put all libraries to link to at the very end of the gcc build command:gcc -Wall -Wextra -Werror -O3 -std=c17 hello_world_extra_basic.c \ -o bin/a -lm -lmyliba -lmylibb -lmylibc -lmylibd
- In short, you technically only need to link to a library
- This answer: Undefined reference to
- So, do this:
- How to use the special Python
__slots__
list inside a class to reduce RAM usage during run-time.- Also, learn about and use class variables vs. instance variables, private variables vs public variables, and internal Python variables surrounded by double underscores (
__some_var__
). Also practice passing and using list args to a function (ex: as*args
), and keyword key:value dict args to a function as well (ex: as**kwargs
). - See "python/slots_practice/slots_practice.py".
- Also, learn about and use class variables vs. instance variables, private variables vs public variables, and internal Python variables surrounded by double underscores (
- How to create, parse, and print YAML files. How to find the directory path a called Python file is in.
- See "python/yaml_import/import_yaml_test.py" and other files in that directory.
- How to autogenerate C or C++ headers or code using Python.
- See "python/autogenerate_c_or_cpp_code.py" and the C or C++ header file it auto-generates: "python/autogenerated/myheader.h".
- File python/raw_bytes_practice.py contains:
- How to convert a list of integers to bytes.
- How to convert bytes back to a list of integers.
- Decoding a bytes buffer into a UTF-8 string.
- Decoding a bytes buffer into an ASCII string.
- Decoding a bytes buffer into a UTF-8 or ASCII string while replacing invalid chars with the 4 char string sequence
"\xhh"
wherehh
is the valid hex char sequence, as a string (via theerrors='backslashreplace'
argument to the bytesdecode()
method). - Converting a bytes buffer into a full hex string.
- Converting a full hex string back into a bytes buffer.
- Also demonstrated in this file:
textwrap.dedent()
- New Python "f" format strings. See: https://realpython.com/python-f-strings/.
time.sleep()
- Exception handling with
try
except
else
.
- Image manipulation:
- How to essentially get the equivalent of GIMP's
Colors --> Auto --> White Balance
feature:- python/auto_white_balance_img.py
- See also my answer on Stack Overflow here for a demonstration and more details: How do I do the equivalent of Gimp's Colors, Auto, White Balance in Python-Fu?.
- How to essentially get the equivalent of GIMP's
- File python/enum_practice.py contains:
- How to use the hash-bang (ex:
#!/usr/bin/python3
) at the top of a Python script to make it a callable file. Note: you must still make the file executable in addition to this too. - How to use enums (ie: "
Enum
classes") in Python. - Demonstrates that Python enums can have values which are either integers or strings (or other types I think too).
- Shows how to left-align prints in Python using the
%
operator, as well as specify their width. This is like theprintf()
-style prints in C and C++. Keywords: python print alignment, python print width, python left or right align prints, python C or C++-like prints, python %s prints. - How to inspect and print all members of any class in Python using the
.__dict__
member accessor; ex:my_obj.__dict__
. - How to access the full, scoped name of an enum with just
my_enum
, or its name withmy_enum.name
, or its value withmy_enum.value
. - How to access an enum via a variable (ex:
fruit
, where previously fruit was set like this:fruit = Fruit.APPLE
) OR directly via its scoped class name (ex:Fruit.APPLE
directly). - How to create an enum class which contains ONLY strings, for instance, by inheriting from BOTH the
str
class and theEnum
class.- Pay attention!: if you try to store an integer into such an Enum class the integer value gets automatically converted into a string! This is demonstrated.
- How to iterate over Enums in Python (meaning: over all enum members in an Enum class).
- Introduce 3 types of enums:
- regular enums
- string enums
- integer enums
- Compare and contrast three types of enums (1. regular enums vs. 2. string enums vs. 3. integer enums), and show and compare how each works and how each treats the
=
operator. - etc.
- How to use the hash-bang (ex:
- Controlling and communicating with Ethernet devices via UDP and TCP communication packets over
socket
s.- These examples demonstrate how to use the built-in Ethernet
socket
module, for instance, to communicate with an Ethernet-controlled device via UDP or TCP. This is very useful for controlling and talking to laboratory equipment, for instance, such as digital power supplies, multimeters, etc. - python/socket_talk_to_ethernet_device.py
- Note:
netcat
(nc
) can be used at the command-line to send commands over TCP and UDP as well. To do essentially the same thing (also over TCP) in the shell command-line as the code does via Python in the file above, do this:printf '%s' "my command to send" | timeout 0.2 nc 192.168.0.1 9999
- Do NOT use
echo
in place ofprintf
above, asecho
appends a trailing newline character (\n
) which can prevent the device from parsing the message properly.echo
is also not very portable and has other limitations such as being unable to send a string which begins with-
. - See my detailed answer here: Stack Overflow: Piping echo to netcat fails while piping printf passes
- See also the many example
netcat
commands in my "git & Linux cmds" doc in my eRCaGuy_dotfiles repo below. Search the document for "netcat". Search also for this section: "Example of power supply control via string commands over Ethernet TCP using netcat". It will be in the document somewhere around here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/git%20%26%20Linux%20cmds%2C%20help%2C%20tips%20%26%20tricks%20-%20Gabriel.txt#L3192-L3219.
- Do NOT use
- Note:
- These examples demonstrate how to use the built-in Ethernet
- c/system_call_python.py - this Python program is autogenerated by and called by the C or C++ program c/system_call_python.c. See additional information about it up above in the "C and C++" section.
- math/sympy_integral_and_printing.py contains symbolic math and integrals in Python.
- github_readme_center_and_align_images.md: show how to insert and center, align left, align right, etc. images in GitHub readmes in markdown. Ex: resize this image to 15% auto-resizing width, and:
Align left:
Align center:
Align right:
6 images in a row:
- See the bash folder.
- See also various *.sh bash scripts I've written in my eRCaGuy_dotfiles repo here: eRCaGuy_dotfiles/useful_scripts.
- How to obtain the full file path, full directory, and base filename of any script being run itself.
- Learn how to use the
source
(AKA.
) command to "import" variables, and theexport
command to "export" them. - How to escape
$
and'
: bash/character_escaping_demo.sh - How to do "array slicing" (like in Python) in bash, meaning: how to grab an element or a desired range of elements from within a bash array. This also covers the bare basics of printing arrays, creating arrays, etc.
- Bash array demo, as well as building and passing arguments to new commands via arrays. See:
- bash/back_up_all_input_args.sh
- bash/array_practice.sh - also shows using negative index numbers to index from the right/end, like in Python.
- bash/check_if_sourced_or_executed.sh
- Identify if a bash script is being executed or sourced (like importing in Python--ex: to get access to its functions), and act accordingly.
- This is the bash-equivalent to Python's
if __name__ == "__main__":
check.
- bash/multi_process_program.sh
- Create a "multi-threaded" (multi-process, actually) bash program, and learn how to start the processes and determine when each is done!
- See also my answer on this here: Stack Overflow: How to wait in bash for several subprocesses to finish, and return exit code !=0 when any subprocess ends with code !=0?
- bash/array_pass_as_bash_parameter.sh
- How to pass arrays as bash parameters to functions or bash scripts in bash.
- This also extensively uses bash array slicing.
- See also my answer here: Stack Overflow: Passing arrays as parameters in bash
- [VERY USEFUL] bash/argument_parsing__3_advanced__gen_prog_template.sh - very complete full program demo. Copy/paste this as a template for all medium to large bash programs! Features:
- Advanced optional and positional argument parsing.
- Full help menu.
- Option to print version info.
- Debug prints which can be turned on/off.
- Function to print arrays.
main
function.- Automatic run vs source detection: if the program detects it is being executed, it will parse arguments and run
main
, but if it detects it is being sourced it will NOT! This way, you can source the program with. path/to/program
orsource path/to/program
to "import" functions and variables you may want from it, but withOUT running it. This is akin toif __name__ == "__main__":
in Python.
- See the awk folder.
- See also: git-diffn.sh in another repo of mine, my readme here, and my answer to how to do "Git diff with line numbers (Git log with line numbers)" here.
- arduino/Blink/Blink.ino - see how to blink built-in LED 13, how to manually "bit-bang" PWM it to dim it, and how to plot a couple opposing sawtooth waves you can view in the Arduino Serial Plotter. Pretty cool!
(Output of tree
. Run this cmd yourself to make sure what you see is up-to-date! I don't update the output below very often.)
eRCaGuy_hello_world$ tree
.
├── arduino
│ └── Leonardo_type_once_per_second
│ └── Leonardo_type_once_per_second.ino
├── avr
│ └── avr_ATmega328_blink--UNTESTED.c
├── awk
│ ├── awk_hello_world_SAMPLE_OUTPUT.txt
│ ├── awk_hello_world.sh
│ ├── awk_syntax_tests.sh
│ └── input_file_1.txt
├── bash
│ ├── array_slicing_demo.sh
│ ├── character_escaping_demo.sh
│ ├── get_script_path.sh
│ ├── Link to ElectricRCAircraftGuy--PDF2SearchablePDF [THIS IS A SOLID BASH EXAMPLE!].desktop
│ ├── Link to PDF2SearchablePDF--pdf2searchablepdf.sh at master · ElectricRCAircraftGuy--PDF2SearchablePDF.desktop
│ ├── practice
│ │ ├── read_arrays.sh
│ │ └── README.md
│ ├── README.md
│ └── source_and_export.sh
├── bin
├── c
│ ├── 2d_array_practice.c
│ ├── assert_practice.c
│ ├── bin
│ │ ├── D_define
│ │ ├── stack_size_bruno_c
│ │ ├── stack_size_bruno_cpp
│ │ ├── stack_size_gs_c
│ │ ├── stack_size_gs_cpp
│ │ └── tmp
│ ├── c - Where do we use .i files and how do we generate them? - Stack Overflow.desktop
│ ├── dynamic_func_call_before_and_after_main_build_and_run.sh
│ ├── dynamic_func_call_before_and_after_main.c
│ ├── gcc_dash_D_macro_define.c
│ ├── hello_world
│ ├── hello_world_basic.c
│ ├── hello_world.c
│ ├── hello_world_sleep
│ ├── hello_world_sleep.c
│ ├── Link to c - Prototype of printf and implementation - Stack Overflow%%%%%+ [MY OWN ANS!].desktop
│ ├── Link to c - Where do we use .i files and how do we generate them - Stack Overflow%%%%% [MY OWN ANS!].desktop
│ ├── Link to Using the GNU Compiler Collection (GCC): Warning Options%%%%% [always use `-Wall -Werror`!].desktop
│ ├── malloc_override_test.c
│ ├── onlinegdb--atomic_block_in_c_WORKS.c
│ ├── onlinegdb--empirically_determine_max_thread_stack_size_Bruno_Haible.c
│ ├── onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c
│ ├── onlinegdb--empirically_determine_max_thread_stack_size.md
│ ├── rounding_integer_division
│ │ ├── c - Rounding integer division (instead of truncating) - Stack Overflow.desktop
│ │ ├── readme.md
│ │ ├── rounding_integer_division.c -> rounding_integer_division.cpp
│ │ ├── rounding_integer_division.cpp
│ │ ├── rounding_integer_division.md
│ │ ├── run_tests_sample_output.txt
│ │ └── run_tests.sh
│ ├── strncmpci.c
│ ├── type_punning.c
│ ├── Using the GNU Compiler Collection (GCC): Warning Options-1.desktop
│ ├── utilities.c
│ └── utilities.h
├── cpp
│ ├── bin
│ │ ├── integer_literals
│ │ ├── onlinegdb--cpp_default_args_practice
│ │ ├── onlinegdb--process_10_bit_video_data
│ │ ├── process_10_bit_video_data
│ │ ├── struct_initialization
│ │ ├── struct_initialization.i
│ │ ├── struct_initialization.ii
│ │ ├── struct_initialization.o
│ │ ├── struct_initialization.s
│ │ └── tmp
│ ├── bin_hello_world
│ │ ├── hello_world
│ │ ├── hello_world.ii
│ │ ├── hello_world.o
│ │ └── hello_world.s
│ ├── check_addr_of_weak_undefined_funcs.cpp
│ ├── copy_constructor_and_assignment_operator
│ │ ├── 170_Copy_Constructor_Assignment_Operator_[Stanford.edu]_GS_edit.pdf
│ │ ├── 170_Copy_Constructor_Assignment_Operator_[Stanford.edu].pdf
│ │ ├── Copy assignment operator - cppreference.com.desktop
│ │ ├── copy_constructor_and_assignment_operator [AKA--the ''Rule of Three'' and the ''Rule of Five'' demo!].txt
│ │ ├── copy_constructor_and_assignment_operator.cpp
│ │ ├── Copy constructors, assignment operators, - C++ Articles-1.desktop
│ │ ├── Copy constructors, assignment operators, - C++ Articles.desktop
│ │ ├── Copy constructor vs assignment operator in C++ - GeeksforGeeks.desktop
│ │ ├── c++ - What is The Rule of Three? - Stack Overflow.desktop
│ │ ├── c++ - What's the difference between assignment operator and copy constructor? - Stack Overflow.desktop
│ │ ├── Link to 170_Copy_Constructor_Assignment_Operator_[Stanford.edu].pdf.desktop
│ │ ├── Link to c++ Assignment operator and copy constructor - Google Search%%%%%.desktop
│ │ ├── Link to Copy constructor vs assignment operator in C++ - GeeksforGeeks%%%%% [see `t2 = t1; -- calls assignment operator, same as "t2.operator=(t1);" `].desktop
│ │ ├── Link to c++ - What is The Rule of Three? - Stack Overflow%%%%%.desktop
│ │ └── Link to When should we write our own assignment operator in C++? - GeeksforGeeks%%%%% [use this code here!].desktop
│ ├── floating_point_resolution
│ │ ├── data -> ../../../eRCaGuy_hello_world_data/cpp/floating_point_resolution/data/
│ │ ├── double_resolution_test_1.cpp
│ │ ├── double_resolution_test_2.cpp
│ │ ├── double_resolution_test_3.cpp
│ │ ├── double_resolution_test_3--Figure_1a.png
│ │ ├── double_resolution_test_3--Figure_1b_zoomed_in.png
│ │ ├── double_resolution_test_3--Figure_1c_zoomed_in_really_small_to_very_beginning.png
│ │ ├── double_resolution_test_4.cpp
│ │ ├── plot_data.py
│ │ ├── readme.md
│ │ └── todo_(what_to_work_on_next).txt
│ ├── hello_world.cpp
│ ├── integer_literals.cpp
│ ├── Link to c - Where do we use .i files and how do we generate them - Stack Overflow%%%%% [MY OWN ANS!].desktop
│ ├── Link to How to initialize a struct to 0 in C++ - Stack Overflow%%%%%+ [my own Q & A].desktop
│ ├── Link to Why doesn't initializing a C++ struct to `= {0}` set all of its members to 0? - Stack Overflow%%%%%++ [my own Q; very good answers here!].desktop
│ ├── macro_practice
│ │ ├── advanced_macro_usage_pass_in_entire_func.cpp
│ │ ├── bin_adv_macro
│ │ │ ├── advanced_macro_usage_pass_in_entire_func
│ │ │ ├── advanced_macro_usage_pass_in_entire_func.ii
│ │ │ ├── advanced_macro_usage_pass_in_entire_func.o
│ │ │ └── advanced_macro_usage_pass_in_entire_func.s
│ │ └── gcc_dash_D_macro_define.c -> ../../c/gcc_dash_D_macro_define.c
│ ├── onlinegdb--atomic_block_in_cpp_1_WORKS.cpp
│ ├── onlinegdb--atomic_block_in_cpp_2_FAILS.cpp
│ ├── onlinegdb--atomic_block_in_cpp_3_WORKS.cpp
│ ├── onlinegdb--const_reference_to_vector__default_func_parameter.cpp
│ ├── onlinegdb--cpp_default_args_practice.cpp
│ ├── process_10_bit_video_data.cpp
│ ├── run_hello_world.sh
│ ├── run_struct_initialization.sh
│ ├── struct_initialization.c -> struct_initialization.cpp
│ ├── struct_initialization.cpp
│ ├── template_function_sized_array_param
│ │ ├── print_array_calls_by_array_size.ods
│ │ ├── readme.md
│ │ ├── regular_func
│ │ ├── regular_func.cpp
│ │ ├── template_func
│ │ └── template_func.cpp
│ ├── template_practice
│ │ ├── explicit_template_specialization.cpp
│ │ ├── research
│ │ │ ├── (7) Template Specialization In C++ - YouTube.desktop
│ │ │ ├── Buckys C++ Programming Tutorials - 61 - Template Specializations - YouTube.desktop
│ │ │ ├── Link to explicit (full) template specialization - cppreference.com%%%%%+.desktop
│ │ │ ├── Link to template c++ - Google Search%%%%%.desktop
│ │ │ ├── Link to template specialization - Google Search%%%%%.desktop
│ │ │ ├── Link to template specialization - Google Search [videos]%%%%%.desktop
│ │ │ ├── partial template specialization - cppreference.com.desktop
│ │ │ ├── Template (C++) - Wikipedia.desktop
│ │ │ ├── Template (C++) - Wikipedia_GS_edit.pdf
│ │ │ └── Template (C++) - Wikipedia.pdf
│ │ └── run_explicit_template_specialization.sh
│ └── unordered_map_practice
│ ├── Link to GDB online Debugger - Code, Compile, Run, Debug online C, C++ [unordered_map practice].desktop
│ ├── unordered_map_hash_table_implicit_key_construction_test
│ └── unordered_map_hash_table_implicit_key_construction_test.cpp
├── eRCaGuy_hello_world--what to work on next--Gabriel.odt
├── git_branch_hash_backups
│ └── eRCaGuy_hello_world_git_branch_bak--20200628-1856hrs-45sec.txt
├── java
│ └── todo.txt
├── LICENSE
├── markdown
│ ├── github_readme_center_and_align_images.md
│ └── photos
│ ├── LICENSE.txt
│ ├── pranksta1.jpg
│ ├── pranksta2.jpg
│ ├── pranksta3.jpg
│ ├── pranksta4.jpg
│ ├── pranksta5.jpg
│ ├── pranksta6.jpg
│ └── pranksta7.jpg
├── python
│ ├── autogenerate_c_or_cpp_code.py
│ ├── autogenerated
│ │ └── myheader.h
│ ├── auto_white_balance_img.py
│ ├── raw_bytes_practice.py
│ ├── slots_practice
│ │ ├── Class and Instance Attributes – Real Python.desktop
│ │ ├── Link to 10. __slots__ Magic — Python Tips 0.1 documentation%%%%%+.desktop
│ │ └── slots_practice.py
│ ├── textwrap_practice_1.py
│ └── yaml_import
│ ├── import_yaml_test.py
│ ├── my_config1.yaml
│ └── my_config2.yaml
├── README.md
├── test_photos
│ ├── README.md
│ └── test1.jpg
└── tree.txt
30 directories, 163 files
- Newest on top
- Follows Semantic Versioning: MAJOR.MINOR.PATCH; see: https://semver.org/ for rules & FAQ.
- The 6 most common recommended types of changes are (see here: https://keepachangelog.com/en/1.0.0/): Added, Changed, Deprecated, Removed, Fixed, Security
INITIAL DEVELOPMENT PHASE:
- Use version numbers 0.MINOR.PATCH for the initial development phase; ex: 0.1.0, 0.2.0, etc.
- Increment just the MINOR version number for each new 0.y.z development phase enhancement, until the project is mature enough that you choose to move to a 1.0.0 release
- You may increment the PATCH number for bug fixes to your development code, or just increment the MINOR version number if there are also enhancements
MORE MATURE PHASE:
- As the project matures, release a 1.0.0 version
- Once you release a 1.0.0 version, do the following (copied from semver.org):
- Given a version number MAJOR.MINOR.PATCH, increment the:
- MAJOR version when you make incompatible API changes,
- MINOR version when you add functionality in a backwards compatible manner, and
- PATCH version when you make backwards compatible bug fixes.
UPDATE 27 DEC 2020: CHANGELOG AND RELEASES NOT REALLY UP-TO-DATE ANYMORE. JUST USE THE LATEST MASTER BRANCH!
- Added "awk" folder with two sample programs: "awk_hello_world.sh" and "awk_syntax_tests.sh"
- Added "cpp/unordered_map_practice/unordered_map_hash_table_implicit_key_construction_test.cpp"
- Added changelog and started tracking a "version" number via the changelog
- Added "python/yaml_import/import_yaml_test.py" and related .yaml configuration files to demonstrate importing and using YAML configuration files in Python
- A bunch of really good C and C++ examples were already in place at this time, as I had been doing this project for quite some time without a Changelog