Clion & Cmake: how to easily create a new class?

I’ve tested the recent Cmake feature, along with CLion which I use for years. Just like the JUCE doc stated, I started a simple project by copying the GuiAppExample. It compiles and runs very fine (on Linux).

Now since the goal is not the use the Projucer, I wanted to create a class with Clion (2021.1 EAP), and expected it to add my new class directly into a CMakeLists.txt file. However, the Create New Class option does not seem to find the obvious target of my project:

I expected “GuiAppExample” to be in the list. Of course it works if I add my class manually in the target_sources, but I expected the IDE to do it by itself. Maybe something in the setup I missed? Thanks!

This is a CLion issue, and you should report it to them (and please do!) in their bug tracker:

https://youtrack.jetbrains.com/issues/CPP

I actually prefer editing the CMakeLists.txt manually, but it would be great if that feature will work correctly in JUCE projects too.

Ok thanks, I was afraid I did something incorrectly. Because if I create a simple project with CLion, this feature works well. As soon as I integrate JUCE into Cmake (using the juce_add_gui_app ‘macro’), the project target cannot be reached anymore.

You can also GLOB all source files in CMakeLists.txt. For example:

FILE(GLOB_RECURSE CPP_FILES "Source/*.cpp")

target_sources(MY-APP PRIVATE
        ${CPP_FILES}
        )

The minor downside is you need to reload CMake when files change e.g. after changing Git branch.

2 Likes

Interesting idea about the GLOB, thanks. It “works” and allows not to have to write the specific file name in the target sources.

However, it requires the CMake to be reloaded, else the new class isn’t taken in account and the link fails (which is a minor downside). But is it a good practice in CMake to “glob” all the source files?

No, not really.

We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.

Sometimes, globbing might be necessary for interop with existing build systems (for example, JUCE’s CMake support uses globbing to locate module sources). If you’re creating a new build from scratch, I’d advise avoiding globbing where possible.

1 Like

Interesting, thanks @reuk - we deliberated a fair bit on this point for a client project, and the client decided to go with globbing in the end. It so far has not caused issues (even on Windows systems), however I’m now more aware of potential issues, thanks.