4

I've run into an issue, I want to compile all my source file but each of them have an main method. My idea was to take cmake and run an for each statement and create the executable for them.

file(GLOB_RECURSE my_c_list RELATIVE ${CMAKE_SOURCE_DIR} "src/*")
foreach(file_path ${my_c_list})
  message(${file_path})
  string( REPLACE ".c" "" name ${file_path} )
  add_executable( ${name} ${my_c_list} )
endforeach()

The folder structure is the followning:

|-- CMakeLists.txt
+-- src
|   +-- Chapter 1
|        +-- 1.0.1
|                someCode.c
|        +-- 1.0.2
|                ohAFunction.c
|   +-- Chapter 2
|        +-- 2.0.1
|                lookCode.c

These snippets come from here

Unfortunately it doesn't work could you help me ?

BTW I run CLion and the CLI both doesn't work.

EDIT: Working CMakeLists.txt

file(GLOB_RECURSE my_c_list RELATIVE ${CMAKE_SOURCE_DIR} "src/*")

foreach(file_path ${my_c_list})
 string( REPLACE ".c" "" new_name ${file_path} )
 get_filename_component(filename ${new_name} NAME)
 add_executable( ${filename} ${file_path} )
endforeach()
S Nell
  • 41
  • 6
  • "it doesn't work" - is not a **problem statement**. If you got an error message, show that message. – Tsyvarev Oct 05 '18 at 13:35
  • That's the problem, i get no message. I think something is wrong with the relative file path. If i had an error message i would post it of course. – S Nell Oct 05 '18 at 13:49
  • Absence of output means that your `file(GLOB_RECURSE)` call found **none** files. Note, that *RELATIVE* options doesn't affect on a way how `file(GLOB_RECURSE)` searches the files; it affects only on output for each file which has been found. Where your `CMakeLists.txt` is located? (Show the place of `CMakeLists.txt` in the file structure you already have in the question post). – Tsyvarev Oct 05 '18 at 14:34
  • 1
    I have updated the structure. – S Nell Oct 05 '18 at 14:44
  • Okay so i tried a bit and i found an mistake. add_executable() should get the parameter ${name} and not ${file_path}. Now the error message is: "The target name "src/myfunk" is reserved or not valid for certain CMake features, such as generator expressions, and may result in undefined behavior." The problem is clear, I need to cut the file path off any ideas ? – S Nell Oct 06 '18 at 10:00
  • Okay never mind, got it to work thanks. – S Nell Oct 06 '18 at 10:46
  • I'm sorry I got error from your working solution: " add_executable cannot create target "a.out" because another target with the same name already exists. The existing target is an executable created in... " – CodyChan Apr 24 '20 at 10:40
  • UPDATE: if all my c/cpp files are in the same directory with CMakeLists.txt, this error happens, if I move all of them into src directory, this works OK. – CodyChan Apr 24 '20 at 10:51
  • UPDATE2: I got it working for my situation: "file(GLOB CPP_workout_list "./**.cpp")" – CodyChan Apr 24 '20 at 11:00

0 Answers0