Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create, Compile, And Run a single file in CLion

Tags:

c++

c

cmake

clion

I am working on some c++ stuff and I hate having to create a whole new project just to run a few things on a file.

I also don't like how when you create a project a file is already called main.cpp.

I just want to make a single file with a few functions or classes. It's not important enough to create a whole project.

I want to create a file and call it what i want. Just create a file what I call, then compile and run.

I don't want to deal with the whole CMake thing, just compile ONE file.

No project related. Thank you.

I know you can do this on visual studio, but i am working on a mac OS X using Clion.

like image 300
Rishi Desai Avatar asked Aug 24 '15 04:08

Rishi Desai


People also ask

How do you create a file in CLion?

In the Project tool window, select the directory in which you want to add new files. Right-click it and select New | C/C++ Source File from the context menu. In the dialog that opens: Specify the name of a file.

How do you compile a file?

To compile all open files, click on the "Compile" button. If you want to just compile a specific file, right click on its name on the left listing of files, and select Compile Current Document. Once the compile is completed, the results are displayed on the Compiler Output tab at the bottom of the screen.


2 Answers

You may modify the CMakeLists.txt

Here an example :

cmake_minimum_required(VERSION 3.3) project(test_build)  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")  set(BUILD_1 main) set(SOURCE_FILES_1 main.cc) //where main.cc is your first main/program add_executable(${BUILD_1} ${SOURCE_FILES_1})  set(BUILD_2 main_2) set(SOURCE_FILES_2 main_2.cc) //where main_2.cc is your second main/program add_executable(${BUILD_2} ${SOURCE_FILES_2}) 

Or use a test (garbage version) :
add_executable(foo bar.cc)

After that you can choose the build you want in CLion

like image 115
Waxo Avatar answered Sep 17 '22 14:09

Waxo


I just had the same question and stumbled upon this thread and then found my solution in this plugin. What this plugin does is basically what user Waxo suggested automatically: adds a single line in CMakeLists.txt for each executable file for you. You just have to right click in editor and select it. I found it pretty useful and use it mostly for algorithms competitions. Hope this helps: https://plugins.jetbrains.com/plugin/8352-c-c--single-file-execution

Cheers!

like image 29
sabak Avatar answered Sep 17 '22 14:09

sabak