A second example using a sub-function

The used code is based on a „cmake“ tutorial example,
but converted from „C++“ to „C“.
The program will be split into several sources in the same directory.

The root „CMakeLists.txt“ (without verbose messages):

The „main.c“ source code:

The sub-directory „mathfunctions/CMakeLists.txt“:

The sources „mysqrt.h“ and „mysqrt.c“:

The compile steps:

Now, in preparation/understanding how to extend a program with additional functions in sub-directories I will add a function calculating the input values third power.

We are learning Now, in preparation/understanding how to extend a program with additional functions in sub-directories I will add a function calculating the input values third power.

We are learning „cmake“ not „C“!

The extended Project Structure:

The extended root „CMakeLists.txt“:

The extended „main.c“:

The additional „my_math_fnctns/CMakeLists.txt“:

The additional sources „thirdpower.h“ and „thirdpower.c“:

The compile steps:

The execution should return something look like this:


One more thing needs to be implemented and tested.
How to use functions specified in a directory outside
of the project structure for common usage by different projects?

For answering this I will create a new example in the next chapter.

A third example using external libraries

Some aditional remarks:

The key „cmake“ concepts for multiple subdirectories

ConceptExplanation
„add_subdirectory()“Called once per subdirectory; creates a target
Target NamesEach „add_library()“ creates a unique target name („mathfunctions“, „my_math_fnctns“)
„target_link_libraries()“Links each library separately to your executable
Include PathsEach library exposes its own headers via „target_include_directories()“
Dependency ChainLibraries can depend on each other if needed (not shown here)


Common Patterns for Scaling

Adding a third subdirectory – just repeat the pattern.

In root „CMakeLists.txt“ add „add_subdirectory(your_third_dir)“ f.e.:

If libraries depend on each other:

Using „find_package()“ instead.

For larger projects, you might use „find_package()“ to locate pre-built libraries:

I will use these suggestions later when creating a real peoject for the RP2xxx.