Use $dir with backslashes escaped in VSCode settings

1.6k views Asked by At

I'm using the Code Runner for [VSCode][2] (Visual Studio Code) and I'm trying to change the run command for C++.

I have the following setting in my settings.json file:

// Set the executor of each language.
"code-runner.executorMap": {
    // ...

    "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"

    // ...
}

Then when I press CTRL SHIFT P and press enter on Run Code to run my current C++ file, it produces the following command to be ran:

cd "c:\C++\" && g++ main.cpp -o main && "c:\C++\"main

But then the output of the command is:

bash: cd: c:\C++" && g++ main.cpp -o main && c:C++"main: No such file or directory

This is because as you can see in the command being run, it's trying to CD to "c:\C++\" but the \ characters are not being escaped and it causes the command to fail. If the command had all the \ characters escaped to look like "c:\\C++\\", it would run correctly.

I am using the git bash console for my integrated terminal.

How can I fix this issue and escape the path's retreived from the $dir variable in my settings.json file?

2

There are 2 answers

0
mirage On

Try out the $dirWithoutTrailingSlash variable instead of $dir.

If that doesn't work, you can try making your own variables in codeManager.js located in %VSCODE_INSTALL%\Data\code\extensions\formulahendry.coderunner-%VERSION%\out\src\.

Add entries to the placeholders array located near line # 246. For example:

{ regex: /\$dirWithoutQuotesNorTrailingSlash/g, replaceValue: this.getCodeFileDirWithoutTrailingSlash() }

which I used to replace

{ regex: /\$dirWithoutTrailingSlash/g, replaceValue: this.quoteFileName(this.getCodeFileDirWithoutTrailingSlash()) }

because I couldn't use variables with explicit quotes in classpaths. You can also define your own function return values (like getCodeFileDirWithoutTrailingSlash) with regex right above it (circa line #222).

0
oleksandrh324110 On

I recommend using make, it's more flexible that way, just create a makefile in the root folder with that content:

all:
    g++ main.cpp -o main.exe
    main.exe

Now you can run all target through the terminal by writing make all or just make (this will run the very first target which is all).


To quickly execute the target via code-runner, add this to settings.json:

"code-runner.executorMap": {
    "cpp": "make -s #", 
}

the -s flag stands for silently, i.e. do not output commands to the console, and # is a comment sign to comment out the path to the file that code-runner will add to the command.