Update: How to format your code:

Open Command Palatte: Format Document

Dependencies

  1. CMake
  2. clang++
  3. clangd

About the cmake project

Download the template for your project here: webpage archive

如果你的“网络不好”,可以尝试这个链接 archive

Most tasks have no headers, but do not delete the include folder:

project-root
|- include
|- source
   |- main.cpp
|- CMakeLists.txt

Demo

Step 1: Get the template

Download the template archive.

Step 2: Open the folder (as your workspace.)

Open Visual Studio Code, and click on

image-20220922183812914

and open the folder.

Step 3: Configure the project

Open Command Palatte

image-20220922184505833

find and click on CMake: Configure:

image-20220922184402551

After configure, VSCode will know the project’s structure.

Step 4: Implement your codes.

In main.cpp you can find the main function:

#include <iostream>

int main() {
  return 0;
}

and the main function does nothing and exit. Let’s do something interesting:

#include <iostream>
using namespace std;
int main() {
  cout << "Hello World" << endl;
  return 0;
}

Step 5: Run the code

Open Command Palatte, and find:

image-20220922185058600

To run, simply click on CMake: Run Without Debugging

You can find the output at the bottom:

image-20220922185159314

(Optional) Step 6: Using Headers

You will learn to seperate functions into multiple files for better developing. For example, you created hello.h and hello.cpp:

image-20220922190120484

Notice: make sure headers in include, and sources in source

Notice: run CMake: Configure right after you created the headers and sources. VSCode may become confused if not run the configure command.

  • hello.h: content is the declaration of some functions
// hello.h: the following line should not be ignored!
#pragma once

void say_hello();
  • hello.cpp: content is the implementation of the functions.
#include <iostream>
#include "hello.h"

void say_hello() {
  std::cout << "Hello World" << std::endl;
}

Now, we can call say_hello in main.cpp:

#include <iostream>
#include "hello.h"
int main() {
  say_hello();
  return 0;
}