This is a very easy question, but I'm struggling unreasonably hard to find answers online.
DeepMind just made MuJoCo free, so I decided to download it on my Windows computer and test it out. When I install, however, all I get is a folder.
I've created a different folder (not inside the downloaded folder), and copy pasted the hello.xml and hello.c files from the tutorial into this new folder. However, VSCode has underlined #include "mujoco.h" in red inside hello.c with the warning cannot open source file "mujoco.h".
I assume that I need to add some things to my path or somehow make my compiler able to find the header file. How should I go about doing this?
Overall, I want to be able to run hello.c.
(I have looked at many different links, which I can link here to prove I've researched elsewhere if needed, but most resources online seem to either 1. Assume things will just work / that you have experience with C and library importing 2. Are for Macs/Linux or 3. Are for mujoco-python)
TL;DR
Create empty visual C++ project
Copy the code
Add MuJoCo Header files via VCC++ Directories -> Include Directories (make sure the set the platform to x64)
Add Library Directories of Mujoco installation ("bin" directory) via Linker -> Input -> Additional Library Directories.
Add the library names (glfw3.lib, mujoco200.lib... etc.) via Linker -> General -> Additional Dependencies
Compile
Put the resulting exe into the bin dir of the MuJoCo installation
Create the project
Open Visual Studio File -> New -> Project -> Visual C++ -> Empty Project
Write the Code
stackoverflowMuJoCo -> Source Files -> Add New Item -> C++ File (I called it "main.cpp" but it shouldn't matter)
Copy the code from hello.c into main.cpp
#include "mujoco.h"
#include "stdio.h"
char error[1000];
mjModel* m;
mjData* d;
int main(void)
{
// activate MuJoCo
mj_activate("mjkey.txt");
// load model from file and check for errors
m = mj_loadXML("../model/hello.xml", NULL, error, 1000);
if( !m )
{
printf("%s\n", error);
return 1;
}
// make data corresponding to model
d = mj_makeData(m);
// run simulation for 10 seconds
while( d->time<10 )
mj_step(m, d);
// free model and data, deactivate
mj_deleteData(d);
mj_deleteModel(m);
mj_deactivate();
return 0;
}
*note i downloaded it before deepmind took over it so I still need to use the mj_activate call but you can just ignore it.
Also i change the path to hello.xml because later i am going to copy the executable into the bin dir of the MuJoCo installation(see below)
Add the header files
Right Click on the Project -> Properties
Change Configuration from whatever is selected (most likely Debug/x86) to "All Configurations" and set the Platform to x64*
VCC++ Directories -> Include Directories
Add the include directories of your MuJoCo installation "mujoco200_win64\mujoco200_win64\include" (should be a path like this)
*this makes sure you don't have to repeat the whole process for every configuration.
VSCode has underlined #include "mujoco.h" in red inside hello.c
This should now be gone.
Add the libraries
Right Click on the Project -> Properties
Configuration Properties -> Linker -> Input -> Additional Dependencies
Enter the names of the .lib files located in your "installation" of MuJoCo
Linker -> General -> Additonal Library Directories add the "mujoco200_win64\mujoco200_win64\bin" directory
The compilation should now succeed but the execution will probably fail
Execution and Debugging
At this stage the execution will probably fail with the following errors message.
To solve this you can just copy the outputed exe file stackoverflowMuJoCo\x64\Release\stackOverflowMuJoCo.exe into the bin directory of your MuJoCo installation.
This will make sure it can find the required dll's.
If you want to be able to debug: manually copy all the dll files into the "stackoverflowMuJoCo\x64\Debug" directory.
Warning
The code from the hello world example is passive simulation this means you won't see anything on the screen.
If you want to see something replace the code with this: https://github.com/atabakd/MuJoCo-Tutorials/blob/master/src/0_preliminaries/pd.cpp and add the invertedPendulum.xml to the models directory.
Some notes
There is probably a better/easier workflow but right now I just tried to get it to work. Also I used a different version of MuJoCo than you but it should basically work the same way (except for the activation stuff).
Installing the C version of MuJoCo 2.2.1 on windows and compiling/running code
(A) Installing MuJoCo and loading a model file
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A1) Navigate to https://github.com/deepmind/mujoco/releases
and download the windows installation, mujoco-2.2.1-windows-x86_64.zip
Unzip this file and put it in a good location (e.g., Documents)
A2) Navigate to bin folder and double click “simulate”. This will open up a GUI.
A3) To load a model, go to the model folder and drop an xml, say humanoid.xml onto the open window. If everything worked fine, you should see a humanoid in the window
(B) Compiling the C programs provided by Deepmind
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
B1) Assuming you have done A1) above
B2) Download the Visual Studio Installer (select community version) here: https://visualstudio.microsoft.com/downloads/
Once the installer has downloaded, run it. When prompted to choose programs, choose the one that says “Desktop development with C++” (see screenshot below). Please restart your computer after installation.

B3) Now we will get some additional libraries to compile and create executables for mujoco on windows. Go to https://github.com/glfw/glfw/releases and download the latex version for Windows (usually glfw-3.x.x.bin.WIN64.zip). Unzip the file.
Now we will drag and drop some files from the glfw folder to mujoco
i) Copy the entire include/GLFW subdirectory to mujoco/include/GLFW.
ii) Copy glfw3dll.lib from the subdirectory corresponding into your compiler (here the compiler is lib-vc2022) to mujoco/lib/glfw3dll.lib.
iii) Copy glfw3.dll from the subdirectory corresponding into your compiler (here the compiler is lib-vc2022) to mujoco/bin/glfw3.dll.
B4) We will open the x64 shell to compile and run MuJoCo. Go to: Start (bottom left corner) —> Visual studio —> x64_Native Tools Command Prompt.
From this shell navigate to the sample folder. Then type make or nmake.
B5) Navigate to bin folder. (cd .. followed by cd bin). Then type simulate. Now you can do A3) above.
This video explains these steps: https://youtu.be/u6tNfvLXK-I
I am trying to learn C programming. And I am using VS Code for running almost everything.
But none of my C Codes execute. The c_cpp_properties.json is configured with the MinGW header files library path included in the "msvc-x64" section. It says "cannot open source file "vcruntime_string.h" (dependency of "string.h")" all the time.
First of all, it's weird that it is not letting you compile by not finding string.h dependency. I suggest to try the following:
Try compiling your files either with gcc or g++ (depending on the language you're using) directly from the terminal, to see if you get the "a.out" file.
Ex: Open your terminal. Find your .c files (if you're programming in C) gcc *.c then ./a.out
Try using CodeBlocks, Build and Run to see if you get the same error.
If 1 or 2 worked, it means your VS software didn't like something when you made the installation process. Reinstall VS.
I had the same problem.
I solved it just by reloading the window.
You can either press Ctrl + R or type "Developer: Reload Window" in the command palette.
You can open the command palette either by pressing Ctrl + Shift + P or going to "View"(up left corner) then "Command Palette..."
I use Clion 2016.1. For example, I run such code in the directory ~/CLionProjects/Tutorial:
#include <stdio.h>
int main() {
char * string;
string = "Hello, everyone";
printf(string);
}
Why does Clion go for this code to this directory?:
/home/ken/.CLion2016.1/system/cmake/generated/Tutorial-9a39f70/9a39f70/Debug/Tutorial
Hello, everyone
Process finished with exit code 15
How to make the programs running in "normal" directory ~/CLionProjects/Tutorial?
UPD
I want to read a "data.csv" file locates in the current directory (where main.c is). But CLion looks for it in /home/ken/.CLion2016.1/system/cmake/generated/Tutorial-9a39f70/9a39f70/Debug/Tutorial. How to make that CLion looks for data.csv in ~/CLionProjects/Tutorial?
If you want to appear your binaries in a folder you've specified, you need to tell it CLion by adjusting your CMakeLists.txt like this:
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/lib)
Edit:
Somehow it seems that these options are not respected in the current version of CLion (2016.2). Therefore one might has to change the desired output directory via: Build, Execution, Deployment | CMake settings and set it there.
For CLion v2016.1 and earlier
To change build output path, open CLion Settings and go to Build, Execution, Deployment | CMake settings and set it there.
This is more an answer for the UPD question than the original. But the answers are related. .EXE is built into a folder that depends on the build options (debug, release, etc). An exe's default working directory is the folder where the exe is found. That is the folder where the program will look for data files, etc, unless you tell it to look elsewhere.
You can change the working directory for the exe with a runtime option. I made a YouTube tutorial for my COSC1030 (Beginning C++) students but the solution is the same for everyone: https://youtu.be/dTtZEAfh_LM
I installed the base package to compile C++ with MinGW Installer GUI and CMake. I created a simple file .c with hello world, and can use cmake . -G"MSYS Makefiles" normally. I added E:\Programmation\MinGW\bin and E:\Programmation\MinGW\msys\1.0\bin to my path.
Here is my CMakeLists.txt:
cmake_minimum_required (VERSION 3.3)
project (Prototype)
set (EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE})
file (
GLOB_RECURSE
source_files
src/*
)
add_executable (
my_exe
${source_files}
)
Once the makefile is created however, when I use make I'll get the following error:
/bin/sh:/e/Users/MyName/Documents/GitHub/ProjectName/prototype/c/E:/Programmation/MinGW/msys/1.0/bin/make.exe: No such file or directory
make.exe": *** [all] Error 127
I can compile the file main.c just fine with gcc main.c and the exe it produces works, so the problem is with the make.exe.
If I use it in the msys.bat shell, located in E:\Programmation\MinGW\msys\1.0, it works as it should. So my guess is that the problem is with Powershell and the path. I'm thinking maybe it's because of the way hard drives are designated, since in the error I get it calls my E:\ disk /e/ first then E:/. When I work in msys.bat I have to write it this way: /e/Users/MyName...
This is PEBKAC. The problem is not with make.exe, but rather, in the way you are attempting to misuse it.
How many times must I say this? Using MSYS make.exe, (or indeed any of the MSYS tools), in any environment other that the MSYS shell, which is started by running msys.bat, is definitively unsupported by the MSYS Project maintainers.
Since you say you problem goes away, when you use make.exe as you are supposed to, (in the MSYS shell, invoked by running msys.bat), this is your problem, and your problem alone. It apparently does not work, when you attempt to use it improperly, (i.e. from PowerShell): that's tough luck; when you break free software, by misusing it, you get to keep all the pieces.
Contrary to the accepted answer, it is actually possible to do this using PowerShell:
sh.exe -c "cd ""$pathToMake""; make"
Make sure you sanitise backslashes for the shell before the call above.
$pathToMake = $pathToMake -replace "\\", "/"
Also the MSYS bin has to be in your path, which would typically look like this (your path maybe different):
$env:Path = "C:\GNUstep\msys\1.0\bin;$($env:Path)"
Is there a way to compile and run a C program from VIM without typing its filename ?
:!gcc -o somename % && ./somename
When using :!, % will be substituted by the name of the currently opened file.
When your project becomes larger, you can also write a makefile and compile the current project with :make, if there are any errors, vim will jump to them automatically.
Use the following mapping code in your .vimrc file for compiling and running a c programming file.
map <F8> : !gcc % && ./a.out <CR>
F8 key is for run the mapping. "%" is to take the current file name.
Or, if you want to save the current file before compiling it, use
map <F8> :w <CR> :!gcc % && ./a.out <CR>
Or more ideally, if you want to use the file basename not the default 'a.out' as the executable file name, use the following:
map <F8> :w <CR> :!gcc % -o %< && ./%< <CR>
In the above command, "<" after "%" removes extension and dot (foo.c => foo), so "%<" is the file basename.
You can find this and similar infos in cmdline.txt. Command in vim:help: cmdline.txt. You can also find specific details about the use of "%" by using :help filename-modifiersin vim.
TL;DR No Makefile is required, tweaking &makeprg is also completely useless, and yet :make %< is enough to compile from Vim.
Long answer:
I duplicate an answer I gave in a closed "duplicate question".
Considering we are using vim, and not vi, :make is the way to go.
On Linux-like (it also applies to cygwin, but not to mingw on windows -- in mingw case, see the other answers that alter &makeprg, leave it alone otherwise) systems where gnumake is installed, if you don't have a Makefile in your project, and if your project is made of only one file, just type :make %<. It will be enough (you can play with $CXXFLAGS, $CFLAGS, $LDFLAGS (for -Llib/path options) and $LDLIBS (for -llibname options) to tune the compilation options). Then to run the program, type :!./%<, or with latter versions of vim, run :terminal ./%<.
If your project is made of several files, then you'll need a Makefile to take advantage of :make.
If you manage your project with CMake, and if you compile your project in a directory (or several -> debug, release, ...) outside the sources tree, then the integration will require a plugin. AFAIK, I'm the only one to propose such a plugin: BuildToolsWrapper integrates the management of CMake (choice of the build directory, possibility to chose between the debug, or release, or whatever build directory). It has to be coupled with one of the local_vimrc plugin.
In all cases, calling directly the compiler from within (or outside) Vim with :!g++ -o %< % or whatever is what we used to do 15 years ago on vi. Vim has a wonderful feature: it can integrate (yes, like in IDE) the compiler. See :h quickfix. Navigating between errors directly from the editor is much easier than extracting one error line with our eyes, typing back the line number into the editor, going back to the shell to see what exactly was rejected, ... It may be enough in C, but In C++ when we are "trying to call an overload that doesn't exist", we can't work this way (switching back and forth between the editor and the shell).
Finally, if you want to compile on a single keystroke those mono-file projects, you can add in your .vimrc:
nnoremap <silent> <f7> :make %<<cr>
If you want to adapt automatically the compilation command depending of the kind of project mono-file pet project, or real world multi-file project, well, more wiring is needed, and this is what BTW does -- it reads various options to know what to do.
Last note: &makeprg is best left alone, at least not set to g++/gcc/clang/clang++/gfortran/... Because, every time you change your language, you'll have to change it (unless you use :setlocal). With the solution I recommend, if I want to use clang++ instead of g++, all I have to do is to set: :let $CXX='clang++' (or $CC in C), and then call :make %<. I can even define :let $CXXFLAGS='-std=c++11' to compile in C++11 -- the same variable will be used to turn warnings on, to use a sanitizer, etc.
It's 2018 now, vim 8 has released for 2 years and shipped with all the Linux distributions and Mac OS X. But a lot of vim tutorials are still teaching people something ten years ago.
You can compile your C++/Java programs in vim as convenience as Sublime Text or NotePad++ with some dedicated plugins for Vim 8 or NeoVim.
For example, the AsyncRun plugin will allow you run shell commands in background and read output from quickfix window in realtime.
See the screen capture.
Just like compiling programs in IDEs, the compilation errors will be matched by errorformat and be highlighted and become selectable. You can navigate errors in the quickfix window or continue editing while compiling.
Quick setup
Copy & paste the lines below to your vimrc:
Plug 'skywind3000/asyncrun.vim'
" open quickfix window automatically when AsyncRun is executed
" set the quickfix window 6 lines height.
let g:asyncrun_open = 6
" ring the bell to notify you job finished
let g:asyncrun_bell = 1
" F10 to toggle quickfix window
nnoremap <F10> :call asyncrun#quickfix_toggle(6)<cr>
When you input “:AsyncRun echo hello ” in the command line:
see the capture here
You will see the realtime command output in the open quickfix window.
Compile and run a single file
Compiling a single file with AsyncRun is much simpler than Sublime Text’s build system. We can setup F9 for this:
noremap <silent> <F9> :AsyncRun gcc -Wall -O2 "$(VIM_FILEPATH)" -o "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
The macros in $(..) form will be expanded as the real file name or directory, and then we will have F5 to run the executable:
noremap <silent> <F5> :AsyncRun -raw -cwd=$(VIM_FILEDIR) "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
The double quotation mark is used to handle path names containing spaces. The option -cwd=$(VIM_FILEDIR) means running the file in the file's directory. The absolute path name $(VIM_FILEDIR)/$(VIM_FILENOEXT) is used because linux needs a ./ prefix to running executables in current directory, but windows doesn't . Using the absolute path name of the binary file can handle this crossing platform issue.
Another option -raw means the output will not be matched by vim's errorformat, and will be displayed in quickfix as what it is. Now you can compile your file with F9, check the compilation errors in quickfix window and press F5 to run the binary.
Build C/C++ Projects
No matter what build tool you are using, make or cmake, project building means acting to a group of files. It requires locating the project root directory. AsyncRun uses a simple method called root markers to identify the project root. The Project Root is identified as the nearest ancestor directory of the current file which contains one of these directories or files:
let g:asyncrun_rootmarks = ['.svn', '.git', '.root', '_darcs']
If none of the parent directories contains these root markers, the directory of the current file is used as the project root. This enables us to use either <root> or $(VIM_ROOT) to represent the project root. and F7 can be setup to build the current project:
noremap <silent> <F7> :AsyncRun -cwd=<root> make <cr>
What if your current project is not in any git or subversion repository ? How to find out where is my project root ? The solution is very simple, just put an empty .root file in your project root, it will be located easily.
Let’s move on, setup F8 to run the current project:
noremap <silent> <F8> :AsyncRun -cwd=<root> -raw make run <cr>
The project will run in its root directory. Of course, you need define the run rule in your own makefile. then remap F6 to test:
noremap <silent> <F6> :AsyncRun -cwd=<root> -raw make test <cr>
If you are using cmake, F4 can be map to update your Makefile:
nnoremap <silent> <F4> :AsyncRun -cwd=<root> cmake . <cr>
Due to the implementation of c runtime, if the process is running is a non-tty environment, all the data in stdout will be buffered until process exits. So, there must be a fflush(stdout) after your printf statement if you want to see the real-time output. or you can close the stdout buffer at the beginning by
setbuf(stdout, NULL);
At the mean time, if you are writing C++ code, a std::endl can be appended to the end of std::cout. It can force flush the stdout buffer. If you are developing on windows, AsyncRun can open a new cmd window for the child process:
nnoremap <silent> <F5> :AsyncRun -cwd=$(VIM_FILEDIR) -mode=4 "$(VIM_FILEDIR)/$(VIM_FILENOEXT)" <cr>
nnoremap <silent> <F8> :AsyncRun -cwd=<root> -mode=4 make run <cr>
Using the option -mode=4 on windows will open a new prompt window to run the command, just like running command line programs in Visual Studio. Finally, we have these key mappings below:
F4: update Makefile with cmake.
F5: run the single file
F6: run project test
F7: build project
F8: run project
F9: compile the single file
F10: toggle quickfix window
It is more like build system in NotePad++ and GEdit. If you are using cmake heavily, you can write a simple shell script located in ~/.vim/script/build.sh to combine F4 and F7 together: it will update Makefile if CMakeList.txt has been changed, then exectute make.
Advanced usage
You can also define shell scripts in your dotfiles repository and execute the script with F3:
nnoremap <F3> :AsyncRun -cwd=<root> sh /path/to/your/dotfiles/script/build_advanced.sh <cr>
The following shell environment variables are defined by AsyncRun:
$VIM_FILEPATH - File name of current buffer with full path
$VIM_FILENAME - File name of current buffer without path
$VIM_FILEDIR - Full path of current buffer without the file name
$VIM_FILEEXT - File extension of current buffer
$VIM_FILENOEXT - File name of current buffer without path and extension
$VIM_CWD - Current directory
$VIM_RELDIR - File path relativize to current directory
$VIM_RELNAME - File name relativize to current directory
$VIM_ROOT - Project root directory
$VIM_CWORD - Current word under cursor
$VIM_CFILE - Current filename under cursor
$VIM_GUI - Is running under gui ?
$VIM_VERSION - Value of v:version
$VIM_COLUMNS - How many columns in vim's screen
$VIM_LINES - How many lines in vim's screen
$VIM_SVRNAME - Value of v:servername for +clientserver usage
All the above environment variables can be used in your build_advanced.sh. Using the external shell script file can do more complex work then a single command.
Grep symbols
Sometimes, If you don't have a well setup environment in you remote linux box, grep is the most cheap way to search symbol definition and references among sources. Now we will have F2 to search keyword under cursor:
if has('win32') || has('win64')
noremap <F2> :AsyncRun! -cwd=<root> grep -n -s -R <C-R><C-W> --include='*.h' --include='*.c*' '<root>' <cr>
else
noremap <F2> :AsyncRun! -cwd=<root> findstr /n /s /C:"<C-R><C-W>" "\%CD\%\*.h" "\%CD\%\*.c*" <cr>
endif
The above script will run grep or findstr in your project root directory, and find symbols in only .c, .cpp and .h files. Now we move around the cursor and press F2, the symbol references in current project will be displayed in the quickfix window immediately.
This simple keymap is enough for most time. And you can improve this script to support more file types or other grep tools in your vimrc .
That’s the practical way to build/run C/C++ projects in Vim 8 or NeoVim. Just like Sublime Text’s build system and NotePad++’s NppExec.
No more outdated vim tutorials again, try something new.
since most of the time you would use a Makefile, in addition to the given answers, I also like to see my results in a "cleared" screen:
map <F10> :w<CR> :!clear; make<CR> :!./%<<CR>
:w<CR> saves the file
:!clear; make<CR> clears the screen and runs make
:!./%<<CR> runs a program (%) without the extension (<)
Add this line in your vimrc file
nnoremap <silent> <F8> :!clear;gcc % -o % && ./%<CR>
Now you only have to press f8 key to compile and run your c program.
Just thought I would add this to these answers here. As has been mentioned, you can use the :make command in vim. What has not been mentioned yet, is that :make can invoke other programs, other than make.
:set makeprg=gcc\ %
Will cause :make to execute gcc with the % symbol replaced by the current file name.
You can then get fancy and do
:set makeprg=gcc\ %\ &&\ ./a.out
and simply typing :make will compile and execute your program. You can do this for other languages as well of course.
:set makeprg=cabal\ repl
:set makeprg=python\ %
After doing some research (including this very page), I made my mind to add this shortcut:
map <F9> :w<CR> :!gcc % -o %<.x -Wall -Wextra 2>errors.err; cat errors.err<CR>
You can also include -ansi -pedantic-errors if you will.
The errors.err file will help you with vi quickfix.
I looked through all of these solutions and I found that they didn't work (as far as I could tell) for the case of editing a file in a different directory -- I wrote some vimscript that does this in a kinda clunky way, but hopefully someone can find this useful:
let mycommand = ':!gcc % -o %< && echo "%<" && [ $(pwd) == "." ] && %< || ./%< '
nnoremap <silent> <F8> :execute mycommand <CR>
or if the commands above work for you in multiple directories feel free to just ignore this.
It may be worth adding that SingleCompile plugin offers that facility for C and other languages as stated by the author:
SingleCompile is a Vim plugin aimed at making it more convenient to
compile or run a single source file without leaving Vim. Consider this
situation: you have just written a small C source file for a tiny
test, but you have to write a Makefile to compile it, or exit Vim to
compile it, or compile it using "!gcc" without quickfix feature
because Vim's make command only use the "make" command? This plugin
will help you out.
Suggested mappings for F9 and F10:
nmap <F9> :SCCompile<cr>
nmap <F10> :SCCompileRun<cr>
I have created command to Run my c & cpp codes
:command Runcpp !clear;g++ % -o %:r && ./%:r<CR>
:command Runc !clear;gcc % -o %:r && ./%:r<CR>
Put above code in .vimrc file and run you code using command Runcpp & Runc
you Can easily compile and run your program from vim directly just go to normal mode and type
:!gcc yourProgramName.c
and then just simply write the following to run the program
:!gcc % | ./a.out
Add these three lines to your .vimrc file
au FileType c set makeprg=gcc\ %
au FileType cpp set makeprg=g++\ %
map <F7>:make && ./a.out<CR>
You can compile and run your program by pressing the F7 button.
I have the following in my vimrc:
autocmd filetype c nnoremap <F9> :w<CR> :!clear<CR> :!gcc % -o %< && %<<CR>
This will allow you to Compile/Run C with <F9> and clear console
You can also do the following:
autocmd filetype c nnoremap <F8> :w<CR> :!clear<CR> :!make && ./%<<CR>
This will allow you to Compile/Run C using Makefile with <F8> and clear console