How to include compiler flags in Visual Studio Code?

The easy option is to pass them as args in your tasks.json configuration:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build-all",
      "type": "shell",
      "args": [
          "-std=c++11",
          "-lfftw3",
          "-L",
          "/path/to/libs",
          "/path/to/file.cpp"
      ],
      "command": "g++",
    }
  ]
}

The more maintainable, shareable option is to create a Makefile and set them all there:

# Specify compiler to be used
CXX = g++
CXXFLAGS += -g -std=c++11 -fPIC -march=x86-64

# Specify paths to headers
INCLUDES += -I include

# Specify paths to the libraries
LDFLAGS  += -L /path/to/libs

# Specify the link libraries
LLIBS    += -lfftw3

# ... add other configs ...

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(OBJ_DIR)
    $(CXX) -c $(CXXFLAGS) $(INCLUDES) $< -o $@

$(OBJ_DIR)/$(PROGRAM): $(OBJS)
    $(CXX) $(LDFLAGS) $^ $(LLIBS) -o $@

Then in your task configuration, just call make:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build-all",
      "type": "shell",
      "options": {
          "cwd": "${workspaceFolder}",
          "env": {
            ...
          }
      },
      "command": "make -f Makefile.x86_64",
    }
  ]
}

If you have env-dependent paths, you can specify a variable in your Makefile (ex. MY_LIBS) and then set them in the env block of the task configuration (ex. "MY_LIBS": "/path/to/libs").

The advantage of the Makefile option is that:

  • People who don’t use VS Code can still compile your code (from console or another IDE).
  • If you are using a CI/CD pipeline, you don’t need a separate configuration. You can use the same Makefile to build locally with VS Code and to build with CI/CD.
  • You can commit the Makefile to a repository, and then just use environment variables in your local tasks.json configuration to specify env-specific settings.

Leave a Comment