CMake 101

(From https://stackoverflow.com/questions/31037882/whats-the-cmake-syntax-to-set-and-use-variables)

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or “What value does my variable have?”

First there are the “Normal Variables” and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory()include()macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the “Global Variables Cache”. Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake’s GUI application before they are generated. Therefore they – in comparison to normal variables – have a type and a docstring. I normally don’t use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.
  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and “How to debug variable changes?”

To avoid pitfalls you should know the following about variables:

  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it’s recommended to use functions()instead of macros() because you don’t want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it’s recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmakeCMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake’s complete parsing process. That’s sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake’s generator writes the make environment (it comparison to normal variables that are replaced “in-place” by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1ONYESTRUEY, or a non-zero number.
    • False if the constant is 0OFFNOFALSENIGNORENOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if (MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if () commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if ("1" STREQUAL "1")
      • if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if ("MSVC" STREQUAL "1")
      • So the best solution here would be – see above – to directly check for if (MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to “only interpret if()arguments as variables or keywords when unquoted.”
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don’t mistake the option with the set command. The value given to option is really only the “initial value” (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake’s GUI.

Android NDK console print C/C++ – Chirag Patel

When your Android app has C/C++ code using NDK tools and you want printing output to serial port console, here’s the solution.

// change sharing first
chmod(“/dev/console”, S_IRWXG | S_IRWXO | S_IRWXU);
// open file
int serialFd = open(“/dev/console”, O_RDWR | O_NONBLOCK | O_NDELAY | O_NOCTTY | O_APPEND);
__android_log_print(ANDROID_LOG_DEBUG, “Serial”, “Serial console fd=%d errno=%d(%s)”, serialFd, errno, strerror(errno));
if (serialFd >= 0) {
    write(serialFd, my_buffer, buffer_length);
    close(serialFd);
}

Beyond Stephen Hawking – Chirag Patel                                2018 April 01

Beyond Stephen Hawking – Chirag Patel                                2018 April 01

#StephenHawking #DarkMatter #DarkEnergy #BeyondBigBang #BigBang #Upanishad

This article is my homage to one of greatest minds of our time – Stephen Hawking.

On 2018 March 02, I read a news article on Stephen Hawking (link: https://www.livescience.com/61914-stephen-hawking-neil-degrasse-tyson-beginning-of-time.html). Hawking said that he knew what it was before big bang! About 13.8 billion years ago, the entire universe was a single atom, Hawking said. In that immensely dense particle of heat and energy, the laws of Physics and Time did not exist! In fact, time tends to nothing infinitely in that tiny speck. There was no point of talking about what happened before that as it did not have any observational consequences, said Hawking.

After reading that, instantly, I thought of atharvashira upanishad! It very well describes how this universe is formed and how it came into existence. Stephen Hawking passed away on 2018 March 14. And since then, I wanted to write this article!

We do not know exact time when atharvashira or any upanishad was written. General belief is that the upanishads were written some 2500-3000 years ago. Traditionally, upanishads are collection of explanation of vedas as taught by rushis to their disciples. So, this oral tradition might very well be 5000-6000 year old!

atharvashira upanishad is also known as atharvashiras or atharvashirsa upanishad. It is a collection of 7 verses describing rudra. It is based on atharva veda. These verses use contemporary words to characterize rudra. Let us analyze some of these words that are very modern and can be compared with modern scientific discoveries.

  1. rudra is indestructible (akshara) and destruclible (kshara).

The world as we know is destructible. Everything around us that we can perceive with our sensory organs goes through cycles of life and death.

Now at subtle level, there is energy and there are elementary particles. These can change their forms but are basically indestructible as long the universe exists. Our universe is the result of big bang. So, when time commenced, there has to be some state of matter and energy that existed before. This can be called seed of the universe and this aspect of universe can be said to be indestructible.

  1. Eight planets (graha) and shadow-planets (pratigraha) are rudra.

When this upanishad was written, people must be aware of planets being distinct objects from stars. Indian astronomical texts suggest eight planets – Sun (soorya), Moon (chandra), Jupiter (bruhaspati), Saturn (shani), Venus (shukra), Mercury (budha), Mars (mangala), Earth (pruthvi). Shadows creating lunar and solar eclipses are called shadow planets (raahu, ketu) in that system. People of ancient time must have a method to identify these objects in sky and that seems to be a remarkable fit.

  1. aumkara is omnipresent and eternal and that is rudra.

One can utter aum without using tongue, teeth and palate. It is primordial sound. And thus, it is primordial energy. So, we can say that this energy or sound must have existed always according to atharvashira upanishad. Also, this sound or energy is all pervading per the upanishad.

  1. aumkara is omnipresent because it is present within everything in this universe as non-manifested entity as oil within sesame seeds. aumkara is eternal because it has no beginning and no end while pronouncing. aumkara is brightest white because it is self-illuminating and gives light to everything else.

These three qualities are remarkable in the sense that they also can be attributed to elementary particles. Every particle can be considered to follow a wave like pattern. And thus, it has sound and vision even though we cannot perceive such subtle properties. So, when we utter aumkara, we are being in tune with primordial universe. This has immense effect at cellular level which we cannot feel but its result is evident at gross level.

Also, 72% of this universe is made up of dark energy. Our cells, atoms everything comprise of dark energy. We do not have direct observational evidences yet. Dark energy is hypothesis. But, this part of the verse states us that dark energy is present in everything of this universe.

  1. Fire (agni), air (vaayu), water (jala), earth (bhoomi) and space (aakaasha) are ashes.

When an object is burnt, its residual matter is ash. Ancient belief was that every matter in this universe is made up of five basic elements – earth, water, fire, air and space. In this verse, it is said that these basic elements are ashes. So, there has to be some objects which were burnt and the result is the formation of the basic elements. We know for sure that Earth is resultant of cooled fire ball. When water vapour cools down, it becomes liquid water. But, vapour is formed if liquid water is heated. So, same can be said for fire, air and space.

  1. This universe is born from rudra in form of fire (agni). When rudra goes to sleep, everything is destroyed. Time (kaala) is born from indestructible element (akshara). Time makes it expanding and all pervading. When rudra breathes, darkness (tama) is born. Liquid (aapah) is created from darkness (tama). rudra churns the liquid (aapah) and it becomes thick (shishira). rudra churns it more and it creates foam (fenah). Cosmic egg (anDa) is born from that foam (fenah). brahmaa comes into existence in that egg (anDa). Air (vaayu) is born from brahmaa. aumkaara is born from air (vaayu). aumkaara creates light (saavitree). Light (saavitree) creates sound (gaayatree). And, sound (gaayatree) creates world (loka).

This universe came into existence through big bang. The above verse describes that whole process in detail. Heat energy and matter were a dense tiny speck which must be the seed for this universe. That seed must be some state of matter and energy which is indestructible as it existed before the beginning of time. As time comes into existence, that seed expands. This verse also states cycle nature of this universe. It has end and it has beginning. In the end, universe just vanishes.

Once time starts from seed, dark matter and dark energy comes into existence in the seed. These dark entities become thick after some churning. More churning makes it less dense and it creates foam. From that foam, cosmic egg forms. First, gaseous matter is formed. This gives birth to primordial energy. That energy generates radiation or light. And the radiation or light brings out sound. Sound creates visual forms and thus this world is born.

Modern science is not able to describe this process in detail yet. We can assume that rushi who wrote this upanishad has definitely some insight into the phenomenon.

 

Fasting – Chirag Patel August 18, 2007

Fasting – Chirag Patel August 18, 2007

Hindus are divided into many different sects. Some sects which are based on “Vaishnava Smpradaya”, asks the followers to do fasting once every month. The Hindu calendar is based on lunar phases. So, every month, the 11th day of waxing moon, is considered the auspicious day to observe fasting.

The basic elements of Hinduism are found in great texts written around 6000 years ago. Bhagavad Gita is one of them which provides very integral terms of Hinduism. This text clearly mandates characteristics of being a Yogi, to lead spiritual path, and to be enlightened. Gita is very much specific about choosing food and having eating habits. According to this great book, offering any substance in pure form to God is the best food. It also cites some substances as leaves, flowers, fruits, and water which are pure and to be offered to God. It states that a true Yogi neither eats more nor eats less.

From later development in vedic texts some 3000 years ago, Patanjali who established a system of “RajaYoga”, declared 8 steps to become a “RajaYogi”. Second step in this system is “Niyama”. This step includes a sub-system called “Tapa”. “Tapa” means habituate mind and body to be in hardship. According to this system, “Tapa” purifies mind and body and makes one ready for advancement in spiritual path.

We can identify two different systems suggested for us – one which favors suffering as habit, and the other that denies any extremities.

Now, let us add a different perspective to this understanding. Physiologically, our body requires energy to digest food. So, if we can fast for half a day or a full day, the saved energy can be utilized for other purposes. People in old time chose some period especially during monsoon which lasts for almost 4 months in India, to do fasting. During this period of year, people feel loss of appetite naturally, and water and/or food have contamination. So, doing frequent fasting during such period allows one to tackle these issues.

In modern era of fasting, people use food cooked with rock salt on the day of fasting. This is not a correct way to do fasting. The whole purpose of fasting is not realized in this case. The best way to fast is to use water only during the day (24 hours period). Some people even prefer not to take water. They do “Nirjala” (literally meaning without water and any food) fasting.

Fasting allows observer to divert attention from food to soul. That allows one to seek path to the truth.

 

Life – Chirag Patel Oct 09, 1998

Life – Chirag Patel Oct 09, 1998

What is life afterall? A little distance
Between two hospitals? Or somthing more?
Life begins with new hope. Life ends
With more hopes. Life is like marathon
Race. A run from little valley of womb
To little valley of mother earth! Truly,
Life is a chase. A chasae of unknown, a
Chase of known! Life is merely this? No.
Life is love. Life is joy. Life is happiness.
Life is relationship. Life is friendship.
Life is giving. Life is uphoria. Aboveall,
Life is a glimpse of God’s activity!

Remembrance – Chirag Patel Jan 10, 1999

Remembrance – Chirag Patel Jan 10, 1999

The first night of life, God asked “Who do you like?”,
Promptuous reply was mine, “Something you life”.

Euphemism it was; which unimpressed creator,
Elaborating, I unfolded truly my needs to narrator.

You like me, you love me, the unforgettable;
Feeling you give us is always fully untouchable.

You like love and I like to be loved forever;
God then created you, not mundane, for ever.

Your touch, your love, your carress, your warmth,
Your care, all made me mad swinging back and forth.

Then went away God, leaving me like a novice;
You taught me to live, yes, you are my choice.

Thankful to God I am. I was rustic, uncultured;
Thankful to you my love, I got pearl from culture.

Rain of Feelings – Chirag Patel Jul 26, 1999

Rain of Feelings – Chirag Patel Jul 26, 1999

Tip, tip, tip; falling drops of rain;
Bathing in; feeling beats of heart drain.

Small creatures; roaming here and there;
Loving them; feeling to go from nowhere.

Breeze of air; scintillating your hair;
Alluring me; feeling to breathe new air.

Diaphanous coat; covering you charming;
Losing control; feeling to seek alarming.

Silver clouds; glittering by the sun;
Giving peace; feeling as if I stunned.

Monsoon everywhere; greenery everywhere;
Togetherness here; feeling deepest love here.

My Love – Diodes Chirag Patel Jun, 1996

My Love – Diodes
Chirag Patel Jun, 1996

Evanescent world, that you are living in;
Lonely diodes, true martyrs you are indeed.

Ever I see, I feel dearth of you;
Carnage of yours, changed the era.

Truly saying, then began the second generation;
Roaming here and there, we met the ICs.

On the way to success, made the neural paths;
Neural networks are the fruits whose seeds you are.

Intellectual Intel made the Pentium;
Consummate – it is indeed; proved-
Success is to flow like water thru’ a road of rocks.

Twinkling Heart – Chirag Patel

Twinkling Heart – Chirag Patel

I want to reach that land farthest.
I want to wander on that land farthest.

All watered mirages of this heart,
All palaces built with sand,
I want to reach that land farthest.

Seeing thru’ eyes of mind,
Fluttering wings of hands,
I want to reach that land farthest.

To receive gift of education,
To give treasure of knowledge,
I want to reach that land farthest.

To enjoy life,
To remove layer of Maya,
I want to reach that land farthest.

Departing from all that were in heart,
With drops of heart from beloved,
I want to reach that land farthest.

O my aunt-land,
I left behind mother for your love.
I am here to explore your womb.
I am here to reap riches.

Please, do not make me cry a lot.
Please, do not remove memories of dear ones.

Let me have memories of my sweetheart,
Accept me at your lotus feet, please.