Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build a cross-platform development environment with VSCode and CMake

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to use VSCode and CMake to build a cross-platform development environment". The editor shows you the operation process through an actual case. The method of operation is simple, fast and practical. I hope that this article "how to use VSCode and CMake to build a cross-platform development environment" can help you solve the problem.

I. Preface

A few days ago, when I was learning to make Breakout games, a practical project of LearnOpenGL tutorials, I hope to develop this Mini Game into a cross-platform one that can run on multiple platforms. If you want to do a good job, you must first sharpen its tools, and the first thing you need to do is to build a comfortable cross-platform development environment, so this article is mainly to record the whole process of building the environment, some holes stepped on, and the corresponding solutions.

Before the text begins, let's elaborate on a few questions.

Why choose to use VSCode

Really unaccustomed to using Visual Studio (or maybe too little T ▽ T)

Code editors prefer lightweight editors, such as Sublime or VSCodeVSCode

It is really powerful and easy to use, and there are plenty of plug-ins.

Why use CMake

General compilation and build tools, cross-platform key, a code, CMake can build for different systems to generate different project projects

Source code control, compilation is more convenient (if you only use VSCode to build the development environment, then each time you add a source file, you have to change the compilation instructions)

The final implementation of the development process is how to write the VSCode code shortcut key Ctrl+Shift+B, call CMake to complete the local project generation (Mac shortcut key Command+Shift+B) shortcut key Ctrl+B, complete the compilation, build and run of the project (Mac shortcut key Command+B) shortcut key F5, complete the debugging and running of the project (F5 debugging run of VSCode, a lot of extra work has been done to realize the debugging function, so it will be a bit slow to start, so when debugging is not needed It will be faster to run directly with Ctrl+B)

II. Development tools

For the acquisition of CMake and VSCodeCMake, please see the official website of CMake.

For the acquisition of VSCode, you can check the official website of VSCode.

It is relatively simple to install CMake and VSCode, and there are many tutorials on the Internet, so I won't introduce them in detail here.

The VSCode plug-in is recommended to be installed in the Extensions panel of VSCode to search for the following plug-in name. Remember to read the author's name clearly and don't put the wrong plug-in.

The plug-in author describes that C/C++Microsoft provides many functions such as code hint, jump, debugging and so on. The official product is that CMaketwxs provides CMake syntax highlighting and code snippet hints. 3. Sample project

The file directory of the example project is not complete, but it is representative, which involves not only the compilation of source code, but also the loading of static library, dynamic library and the reading of resource files.

Breakout

├── 3rd / / third-party library

│ ├── glfw / / A directory of static libraries

│ ├── irrKlang-1.6.0 / / A directory of dynamic libraries

│ └── FindIrrKlang.cmake / / cmake file

├── resources / / Resource Directory

│ ├── textures / / stores the map file

│ └── shaders / / stores shader files

├── src / / source code directory

│ ├── game / / Source Code subdirectory

│ │ ├── game.h

│ │ └── game.cc

│ └── main.cc

└── CMakeLists.txt / / cmake file

4. Use CMake

This article only focuses on some cmake statements used to complete the development of the sample project and solve specific problems.

All the statements of cmake are written in CMakeLists.txt, and cmake will complete a series of tasks such as compiling, building, packaging, testing and so on according to the configuration in this file.

A simple CMakeLists.txt is shown below, and the complete file can be seen here

# cmake minimum version number requirement

Cmake_minimum_required (VERSION 2.8)

# set PROJECT_NAME variable

Set (PROJECT_NAME Breakout)

# set the project name

Project (${PROJECT_NAME})

# find all source files in the current directory and store them in the DIR_SRCS variable

Aux_source_directory (src DIR_SRCS)

# add a compilable target to the project

Add_executable (${PROJECT_NAME} ${DIR_SRCS})

How to compile all source code in a folder

In the process of development, because of the architecture design or in order to facilitate management and search, the source files are generally stored in different folders according to different functions, and folders may be embedded in the folders. so you need a statement that can get all the source files for compilation, instead of modifying the compilation instructions every time you create a new source file.

# Recursively list all source files

File (GLOB_RECURSE SOURCE_FILES * .cc)

# add a compilable target to the project

Add_executable (${PROJECT_NAME} ${SOURCE_FILES})

The above file command recursively lists all .cc files, stores them in the SOURCE_FILES variable, and then adds all .cc files represented by SOURCE_FILES to the target, thus solving the problem of compiling multi-source files.

4.1. How to introduce a third-party static library

In order not to repeat the wheel, it is inevitable to introduce other third-party libraries in the development. Normally, this third-party library will also be a CMake project (or the developer of the library will directly provide the compiled library)

Take the glfw library introduced by the sample project as an example

1. Add submodule to introduce glfw (glfw happens to be an open source project on github), or put the source code of third-party libraries directly into your own directory

Git submodule add https://github.com/glfw/glfw.git

two。 Use the add_subdirectory command to add the folder where glfw is located to the compiled task list

# ensure that glfw dir is compiled

Add_subdirectory (${GLFW_DIR})

3. Add the header file directory of glfw to the header file search path

# add header file search path

Include_directories (${GLFW_DIR} / include)

4. Link the glfw library. The target_link_libraries command is used to link the target and the library file. The first parameter is our construction target, followed by multiple parameters to link multiple libraries.

# add a link library

Target_link_libraries (${PROJECT_NAME} glfw)

4.2. Loading of dynamic library

Take the irrKlang library introduced by the sample project as an example, it is not an open source project, but fortunately it provides libraries that have been compiled on multiple platforms, so we need to set up and introduce different library files according to different platforms.

1. Using find_package to introduce external dependency packages, it can help us find many official predefined dependency package modules. When not found in the official predefined dependencies, we will look for the FindXXX.cmake file and execute the file to find the XXX library.

# IrrKlang

Find_package (IrrKlang REQUIRED)

two。 First create a new FindIrrKlang.cmake file, which is responsible for loading the specific irrKlang library. Some of the statements are shown below, mainly according to the current platform, set different header file path, library path, library directory and other variables. The find_library statement used can directly base on the base name of the library (that is, it does not need lib,so, etc.), find the corresponding library, and store the IRRKLANG_LIBRARY variable.

Find_path (IRRKLANG_INCLUDE_DIR NAMES irrKlang.h PATHS "${3RD_DIR} / irrKlang-1.6.0/include") IF (WIN32) # win32 platform if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") message (STATUS "Using MSVC") set (IRRKLANG_LIB_DIR "${3RD_DIR} / irrKlang-1.6.0/lib/Win32-visualStudio") set (IRRKLANG_BIN_DIR "${3RD_DIR} / irrKlang-1.6.0/bin/Win32-visualStudio") find_library (IRRKLANG_LIBRARY NAMES irrKlang PATHS ${IRRKLANG_LIB_DIR}) elseif ("${CMAKE_CXX_COMPILED_ID}" STREQUAL "GNU") message (STATUS "Using GCC") set (IRRKLANG_LIB_DIR "${3RD_DIR} / irrKlang-1.6.0/lib/Win32-gcc") set (IRRKLANG _ BIN_DIR "${3RD_DIR} / irrKlang-1.6.0/bin/Win32-gcc") find_library (IRRKLANG_LIBRARY NAMES libirrKlang.a PATHS ${IRRKLANG_LIB_DIR}) endif () elseif (APPLE) # mac platform set (IRRKLANG_BIN_DIR "${3RD_DIR} / irrKlang-1.6.0/bin/macosx-gcc") find_library (IRRKLANG_LIBRARY NAMES libirrklang.dylib PATHS "${3RD_DIR} / IrrKlang-1.6.0/bin/macosx-gcc ") elseif (UNIX AND NOT APPLE) # is equivalent to linux platform set (IRRKLANG_BIN_DIR" ${3RD_DIR} / irrKlang-1.6.0/bin/inux-gcc ") find_library (IRRKLANG_LIBRARY NAMES IrrKlang PATHS" ${3RD_DIR} / irrKlang-1.6.0/bin/linux-gcc ") endif ()

3. Add the found irrKlan header file to the header file search path

Include_directories (${IRRKLANG_INCLUDE_DIR})

4. Link irrKlang Library

# add a link library

Target_link_libraries (${PROJECT_NAME} glfw ${IRRKLANG_LIBRARY})

4.3.The error report of the code in utf-8 format compiled by visual studio

Cross-platform code, generally using utf-8 coding format, is more general, and can also ensure normal compilation on MacOS or Linux platforms.

But the visual studio default compilation file is utf-8 with bom, in the absence of Chinese, direct compilation is no problem, however, when the source file contains Chinese (such as Chinese comments), there may be exceptions, reporting some inexplicable syntax errors. The solution is to tell MSVC to compile with utf-8 encoding through the CMake statement.

# set MSVC compilation coding

Add_compile_options ("$")

4.4. The working directory of executable files

After compiling the build to generate the executable, we want to be able to start the executable directly through the command line command to see the effect. However, due to the problem of the working directory, it may lead to the problem that the resource file cannot be found, or the library load fails.

For the visual studio project, you can set its working directory through the CMake statement, but this working directory will only take effect when it is started through visual studio debugging, but it is still useless for directly starting the executable

# set working directory

Set_property (TARGET ${PROJECT_NAME} PROPERTY VS_DEBUGGER_WORKING_DIRECTORY

${CMAKE_SOURCE_DIR} / resources

)

Therefore, you can only place the resource file directory in the same directory as the executable file to ensure that it can be loaded into the required resources, which can be achieved through the custom command of CMake.

# copy resource files to the working directory

Add_custom_command (TARGET ${PROJECT_NAME} POST_BUILD

COMMAND ${CMAKE_COMMAND}-E copy_directory

${CMAKE_SOURCE_DIR} / resources

$/ resources

)

The function of this statement is to copy the specified resource directory to the directory where the generated executable is located after compilation.

Similarly, some dynamic libraries, such as dylib,dll, also need to be copied, but it is best to copy them to the target directory before compilation, using PRE_BUILD to indicate the timing of command execution.

# copy the library to the working directory

Add_custom_command (TARGET ${PROJECT_NAME} PRE_BUILD

COMMAND ${CMAKE_COMMAND}-E copy_directory

${IRRKLANG_BIN_DIR}

$

)

4.5.How to modify the loading path of dynamic libraries on Mac

When starting the executable on Mac, I always encountered an error that the dynamic library could not load.

Dyld: Library not loaded: / usr/local/lib/libirrklang.dylib

Referenced from:...

Reason: image not found

This is because when compiling and generating a dynamic library, you can specify the loading path of the dynamic library. For example, the libirrklang library we introduced defaults to looking for dylib files in the / usr/local/lib directory.

The simple solution, of course, is to install the libirrklang.dylib file into the / usr/local/lib directory through the install command, but in order not to "pollute" other directories, we prefer the executable file to load the libirrklang.dylib file in its directory. To achieve this goal, we add the following CMake statement

If (APPLE)

Add_custom_command (TARGET ${PROJECT_NAME} POST_BUILD

COMMAND install_name_tool-change / usr/local/lib/libirrklang.dylib @ executable_path/libirrklang.dylib ${PROJECT_NAME}

)

Endif ()

If it is the Mac platform, call the install_name_tool command through add_custom_command to modify the search path of the application to the dynamic library. The @ executable_path indicates the directory where the executable file is located

Use the task.json of VSCode to execute the specified command

The configuration file of CMake is basically ready, and then there is the question of how to call CMake more conveniently with VSCode.

5.1.Executing CMake to compile local projects through Ctrl+Shift+B

Ctrl+Shift+B is the default shortcut key for VSCode to call task. Task is defined in the task.json file in the .vscode directory. Task is generally used to complete compilation and other tasks. The VSCode task system provides rich parameter configuration, and we can use it to complete many custom tasks.

Define a task and execute cmake.. Command to complete the compilation and generation of the local project. Linux generates Makefile,MacOS to generate Makefile or Xcode project, and Visual Studio project under Windows. Pay attention to the... Represents the upper directory, because we will create a new build folder under the root of the project, and then complete a series of compilation work in this folder, so that the intermediate files generated by cmake are in the build directory and will not "pollute" the development directory (adding the build directory to .gitignorej can ignore all the intermediate files generated by CMake). When there is a compilation problem, you can directly delete the buidl directory and recompile.

{"label": "cmake", / / name of task "type": "shell", "command": "cmake", "args": [/ / "- DCMAKE_BUILD_TYPE=$ {input:CMAKE_BUILD_TYPE}", ".."], "options": {"cwd": "build" / / indicates the current execution directory build folder} "group": "build", "presentation": {/ / some console display configurations "echo": true, "reveal": "always", "focus": false, "panel": "shared", "showReuseMessage": true, "clear": true}, / / Use the standard MS compiler pattern to detect errors, warnings and infos "problemMatcher": "$msCompile" "dependsOn": ["mkbuild"] / / dependent task Execute the mkbuild task before this task is executed}

In cmake.. Create a new build folder by executing mkdir through task before the command is executed. The windows parameter is used to distinguish different parameters set by different platforms.

{"label": "mkbuild", "type": "shell", "command": "mkdir", / / called command "args": [/ / command parameter "- p", "build"], "windows": {/ / windows platform uses mkdir-Force build to create a new folder "args": ["- Force" "build"]}, "group": "build", "presentation": {"echo": true, "reveal": "always", "focus": false, "panel": "shared", "showReuseMessage": true, "clear": true}, / / Use the standard MS compiler pattern to detect errors Warnings and infos "problemMatcher": "$msCompile",}

When Ctrl+Shift+B is pressed, VSCode will pop up all executable task, and select execute cmake task. Because dependency (dependsOn) is defined, mkbuild task will be executed automatically before cmak task execution

5.2. build and run executable files through Ctrl+B

Before starting the executable file, use cmake-- build. Build to generate executable file

{"label": "compile", "type": "shell", "command": "cmake-build.", "options": {"cwd": "build"}, "group": "build", "presentation": {/ / Reveal the output only if unrecognized errors occur. "reveal": "always", "clear": true}, / / Use the standard MS compiler pattern to detect errors, warnings and infos "problemMatcher": "$msCompile"}

After the executable file is generated, start the executable file through task. Where ${workspaceFolderBasename} is the built-in variable of VSCode and represents the project name. More descriptions of built-in variables can be found here

{"label": "run", "type": "shell", "command": ". / ${workspaceFolderBasename}", "group": "build", "presentation": {"echo": true, "reveal": "always", "focus": false, "panel": "shared", "showReuseMessage": true, "clear": true} "options": {"cwd": "build"}, "windows": {"options": {"cwd": "build/Debug" / / windows visual studio project will generate more Debug/Release directories by default},}, / / Use the standard MS compiler pattern to detect errors, warnings and infos "problemMatcher": "$msCompile" "dependsOn": ["compile"] / / execute the run task before the compile task executes Make sure the modified code takes effect}

Invoke the run task directly through Ctrl+B. Because compiling and running this task is often used, it will be troublesome to choose further if all the tasks are still popped up through Ctrl+Shift+B, so define a shortcut key (readers can set their favorite shortcut key in the same way) to directly run the run task to open the VSCode shortcut key setting.

Enter "run build task" to search in the pop-up interface and modify its shortcut keys

Click the flip button in the upper right corner to enter the shortcut key file configuration

In the open file, add parameters to the shortcut key you just configured and tell it to start the task named "run" directly.

{"key": "ctrl+b", "command": "workbench.action.tasks.runTask", "args": "run"} VI. Use launch.json of VSCode to complete debugging

VSCode implements debugging support for multiple platforms and languages through launch.json under .vscode directory.

Complete the debugging of the project and run the configuration launch.json file through F5 to support the debugging of the Cumberbatch + project.

{/ / Use IntelliSense to learn about possible attributes. / / Hover to view descriptions of existing attributes. / / For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [{"name": "Launch Debug", / / name "type": "cppdbg", / / debugging type, except for debugging using msvc All of them are of this type "request": "launch", "program": "${workspaceFolder} / build/$ {workspaceFolderBasename}", / / specify the location of the program "args": [], / / specify the running parameters "stopAtEntry": false, "cwd": "${workspaceFolder} / build" / / specify the working directory "preLaunchTask": "compile", / / call this task to compile the builder "environment": [], "externalConsole": false, "osx": {/ / specific configuration of macOS / / "miDebuggerPath": "/ Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi" before debugging / / modify the lldb-mi used Generally, there is no need to modify "MIMode": "lldb" / / specify to use lldb for debugging}, "linux": {/ / specific configuration of linux "MIMode": "gdb" / / specify to debug "setupCommands" using gdb: [{"description": "Enable pretty-printing for gdb", "text": "- enable-pretty-printing", "ignoreFailures": true}]} "windows": {/ / specific configuration of windows "type": "cppvsdbg", / / specify the use of msvc for debugging "program": "${workspaceFolder} / build/Debug/$ {workspaceFolderBasename} .exe", / / specify the location}}]}

F5 is the default shortcut key for VSCode debugging, and no additional configuration is required. The interface after starting debugging is as follows

Debug by using native tools. Since cmake will generate Visual Stduio project by default on windows platform, you can also open the generated solution directly. Debugging Mac platform through Visual Studio can use cmake.. The-GXcode command specifies that the XCode project is generated and then debugged through XCode

That's all for "how to use VSCode and CMake to build a cross-platform CumberCraft + development environment". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report