I am new to Visual Studio Code and I am just starting to learn the basics of using it to compile my C++ projects. I have ran into an issue where when having a folder 'opened' in Vs code, and then having an inner folder with my 'main.cpp' file inside of it, when compiled creates the 'main.exe' outside of the innerfolder, I don't want this to happen and want the executable which belongs to that main.cpp, inside of the inner folder so that both are stored in the same folder, to me that makes more sense than it being outside of the intended folder. I really don't know where to look to change this behaviour.
Here is an example of what I mean:
Update: Will post an answer to my own problem soon
Update2: I answered it in full detail for anyone ever having this problem/question
I came up with an easy solution. You only have to hide the files with extension .exe. With your answer many people get confused so you have to follow some steps.
step 1: go to files
step 2 : click on preferences-->then settings
step 3 : then search for "exclude file"
step 4 : select add pattern
step 5 : "**/*.exe" add this -->then click ok
step 6 : close the visual studio code then open it again
The process is very simple.
The following process shows how to create/make executable/.exe file in your provided/specific folder
goto Command Palette... by pressing Ctrl + Shift + P
press Backspace to remove > symbol
search tasks.json file, and hit Enter
-. in tasks.json file, you have to look for the following code (Note: this code can be shown 2 or 3 times in the file. Perform the operation for everyone)
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
replace the code "${fileDirname}\${fileBasenameNoExtension}.exe" with your new path, for example, i have a new folder named as "myNewFolder" in my workspace foler, i will replace it as
"${fileDirname}\myNewFolder\${fileBasenameNoExtension}.exe"
hit Ctrl + s to save changes
Now, the following process shows how to run/launch your executable/.exe file provide in your allocated folder/location
goto Command Palette... by pressing Ctrl + Shift + P
press Backspace to remove > symbol
search launch.json file, and hit Enter
look for the key named as "program"
-. it will be as follows
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
change the filepath. in my case, i will change it as follows
"program": "${fileDirname}\myNewFolder\$fileBasenameNoExtension}.exe",
Save changes
If you're using Code Runner extension, then :
Press Ctrl + Shift + P
step1
delete the ">" symbol (press Backspace to delete)
search "settings.json" which in AppData directory
step3
then you can look at "code-runner.executorMap", in "cpp" line. You can type that arguments
"code-runner.executorMap": {
"javascript": "node",
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
"c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt", // <-- This
"objective-c": "cd $dir && gcc -framework Cocoa $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"php": "php",
"python": "python -u",
//etc.
},
"code-runner.runInTerminal": true,
Note :
Actually the argument in step 4 is default settings. So, you don't have to edit it if it's your first time using it.
but if u want to customize the argument (in most cases is used to change the output directory), that is the place you'll be used for.
e.g. in my case, I want to separate the .cpp and .exe files to "src" and "bin" folder, so :
"cpp": "cd $dir && g++ $fileName -o ..\\bin\\$fileNameWithoutExt && ..\\bin\\$fileNameWithoutExt",
result :
The separate folder look like : folder_screenshot
Terminal :
PS C:\Coding\C++\src> cd "c:\Coding\C++\src\" ; if ($?) { g++ string.cpp -o ..\bin\string } ; if ($?) { ..\bin\string }
Hi
Hope it works
PLEASE READ IT IS A FULL AND VERY DETAILED EXPLANATON ON A POTENTIAL BUG, WHICH COULD AFFECT WORKFLOW, VISUAL STUDIO HAS YET TO FIX THIS! I WILL REPORT THIS AS SOON AS POSSIBLE
So I've been ripping my hairs out my head with this non-sense of a problem, but finally I have come to a conclusion that Visual Studio has a very hidden bug (since I was not able to find anyone with a similar question/problem), or very unclear documentation.
The initial problem was that if I were to have (I will give a clearer example below) an outer folder opened in Visual Studio Code with an inner folder inside which had the main.cpp file, Visual Studio Code would not budge and would put the main.exe file in the outer folder and not the inner one, you can imagine why this would become a problem if I had many other inner folders inside the outer one and all had their exe file called main.exe.
Let me give you an example of what I mean:
Suppose I have the following path (with main.cpp already having code inside) - outer-folder\inner-folder\main.cpp
Now I open the outer-folder in Visual Studio Code. The following is what it should look like if opened in Visual Studio Code for the first time, without having built or compiled anything
After opening outer-folder for the first time in Visual Studio Code
If I were to try and Ctrl + F5 this now, using the option given by Visual Studio Code of... C++ (GDB/LLDB) ---> g++.exe - build and debug active file, the following would be seen on screen:
After Ctrl + F5 and following options as stated in my explanation
In this case I am in my D: drive and in the example path stated at the beginning of my explanation. The error is saying that main.exe doesn't exist in the inner-folder, which is completely true, it exists inside the outer-folder. Why? Because we need to edit the tasks.json (already misleading information by Visual Studio Code, by inclining me to open the launch.json file, although they are correct to some extent since it is saying launch.json can't find the file to launch so maybe you got your path wrong in there, it would be helpful to also have another option for the tasks.json) which is located in the folder automatically made by Visual Studio Code .vscode along with launch.json.
When in the tasks.json file, there is a variable (if you may call that, though I think there is a different name for that), called args...inside that ([]) are the arguments that Visual Studio Code automatically passes in to the terminal to compile and build your C++ code. The details of all the arguments passed in aren't important for this problem, but the second one (${file}) is referring to the file which we are trying to run, as stated in https://code.visualstudio.com/docs/editor/variables-reference (keep this open as we will need it), the next one (-o) is just telling it to output it like and where the forth argument specifies. The forth one is the really important one here, if we go back to the link which has a reference of the variables that Visual Studio Code provides, ${fileDirname} "should" infact mean the same as saying outer-folder\inner-folder...right? NO! It is wrong, it is actually saying outer-folder, which is the reason why main.exe is being built outside of inner-folder, so we already have a red flag of some type of misinformation from the docs or some type of bug.
Now as the docs that Visual Studio Code provide about gcc on VSC (https://code.visualstudio.com/docs/cpp/config-mingw) we can change somethings, so that the program is built and output in a different location, to do so we need to go into the tasks.json and from there changing the forth argument in args to ${fileDirname}\\inner-folder\\${fileBasenameNoExtension}.exe, now don't reach for the Ctrl + F5 key yet, I need to explain why that won't work, but first let's try something out...press Ctrl + Shift + B, that will build your program but not run it (if you are following this make sure to be building the correct file and not trying to build tasks.json itself lol), now when we do that we can see that another main.exe file will have been built and output in the correct location output is in the correct location. Ok now the docs on configuring mingw in Visual Studio Code suggest than now you can run your file by going to the terminal and running it from there (no need for an explanation on how to do that). What is the fun in that though what if you want to debug it? Here is where we are going to find another potential bug or very bad documentation surrounding this. If we open our launch.json now (this is the file that is ran when you press Ctrl + F5) and then we look at the variable (again I'm nearly 100% sure that is not what it is called but I don't know what to call it at this point) program: here is where you tell launch.json where the location to the file you want to run is, in our case it is where our main.exe should be located. Since we have fixed the issue with in the tasks.json and can now build with Ctrl + Shift + B every time we want to rebuild in the right location, we can now run with Ctrl + F5, right? NOPE! This is where the next bug/bad documentation comes along! If you look at the very bottom of the file there is a "preLaunchTask:" this is the name of the value stored in "label": back in our tasks.json, and it has to match perfectly so that launch.json knows which task to run when invoked. The problem is that even though they match automatically already (as their names are the same by default), it still doesn't work, Visual Studio Code for some reason say, YOU KNOW WHAT SACK YOUR TASKS.JSON WE WILL OVERWRITE THAT AND USE THE DEFAULT ONE! Even if your the default name matches the default on launch.json, it doesn't run your tasks.json it overwrites it with the default one (not 100% sure what it does but that is my best guess, as it 100% doesn't run our one), now the interesting bit is that when we change both the "preLaunchTask": and the "label": to the same thing just anything else than the default one (even add one more character anywhere but make sure both match), when we do Ctrl + F5 it now runs our tasks.json! Yet... all of this for nothing because at the end of the day we had to hard code that tasks.json and we would have to do that for every file that we want stored in some other inner folder! You can fix this (as I later found out) by just opening that folder (inner-folder) as the main one instead of the outer-folder, and boom problems fixed, but then you can't see your whole project as you would have been able to, had your outer-folder been opened.
Related
I have installed g++ on Windows.Later I added the compiler path to the windows 10 environment variables.But how can i add g++ compiler on visual studio code? I tried many guides on youtube but they didn't help me, in fact I can't see the lunch.json file
If you don't already have a task file: Create a task file, so tasks.json in .vscode. If you don't already have one, open the command pallet (it's in view) and type task then press configure task file.
If you do have a task file: Once you have the task file in command type
"command": "{Path to g++.exe}\\g++.exe", with \\ for directories instead of / or \.
Mine is "G:\\Apps\\MinGW\\bin\\g++.exe".
Then, Ctrl+Shift+b in the file you want to compile and press your task file.
I'm new in C++, I just started learning and I watch tutorials on youtube. Even though I did everything right, I download compile (g++) etc.. My simple code is not working:
#include <iostream>
int main()
{
std::cout << "Hello World\n";
return 0;
}
and it gives me this error:
g++ : The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was include
d, verify that the path is correct and try again.
At line:1 char:1
+ g++ number1.cpp
+ ~~~
+ CategoryInfo : ObjectNotFound: (g++:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Can anyone help?
I don’t know c++ never have i coded in it.
But by seeing into your error it seems your g++ compiler is not installed properly. Or if it is installed properly then you forgot to add it into your windows environmental variables.
This error is mainly because you might have not added the PATH to your bin folder (MinGW) in Environment Variable.
https://stackoverflow.com/a/65529400/14002303
You can check the above answer.
I thing you have installed before Mingw , so 99% the problem, is this:
add the PATH to your bin folder in Environment Variable.
1. open folder
2. click this pc (folder)
3. Click mingw folder
4. click Bin folder
5. now to copy the path from the top
C:\MinGW\bin
6. go another time to MY PC folder
7. now click in the FREE SPACE with your right-click-mouse
what is mean right-click?
ok.
8. click properties
now you have a UI like this:
9. click Advanced system settings
10. click on Environment variable
now the UI is like this:
11. click on Path, the Click Edit...
now the UI is like this:
12. now click NEW on the right of the UI of this windows.
now you have 1 more line in the right of this UI :) where you can put your text
13. NOW paste the bin directory in the text-input UI widget
C:\MinGW\bin
14. now click OK in the bottom in every opened windows
15. now check if g++ is setup correctly
**a. first, open terminal **
b. write g++ --version
g++ --version
if is returning something, this is amazing! , no problems in the future :)
need more details on how to setup g++? :
here a video tutorial on this i found for you
not correct?
try use instead g++ dont use gcc
if you dont know how to execute,
very simple way is (since you have installed this compiler) :
download a extension for vscode, for example code runner
now you can click in the top-right the green ▶ triangle button. or CTRL + ALT + N
code runner write for you the terminal code
OR
click CTRL + ALT + B (but this only create .exe file, then you need to open the .exe file)
OR MANUALLY
you need first go to your folder using: cd
you need now the name of folder (where the code .cpp is inside)
click on terminal, and type the name of the folder
example: cd YourFolderName
trick:
click TAB for searching the folder in the fast way :)
now write g++
(and using the trick of TAB, write name of program c++)
write name of program .cpp
now you have a .exe file created for you
just put the name of .exe
without g++
something like this:
g++ NameOfCppFile.cpp
usually the name of .exe file is a.exe
if you want your .exe file having a custom name
just put -o nameOfExeYouWant
so something like this
g++ NameOfCppFile.cpp -o NameOfFile
First off I would like to say I've seen the previous questions on this site, I've tried every solution but none fit my use case or solves my problem.
I am having trouble with the g++ complier being recognized, I've included this path:
C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe
which is where the current version of mingw is located (recently downloaded). I've also tried other options like changing the path to gcc.exe, and just regular bin. Someone please provide a detailed solution to this problem.
Other things i have tried and looked at closely would be:
http://stephencoakley.com/2015/01/21/guide-setting-up-a-simple-c-development-environment-on-windows
seeing as though I'm working through sublime text 3
Another thing Ive tried:
Ive tried to copy and paste the path into cmd and run it , but i find this error code:
C:\Users\Kxrk>C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
So seeing that, i tried another way , and that is to drag the file and drop it into cmd and get this :
C:\Users\Kxrk>C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe
g++.exe: fatal error no input files
compilation terminated
when u drag and drop the file it has double quotes around it , so i tried editing the path to contain double quotes around it and the path automaticlly changes back after saving.
This was very simple , it was one of those weird cases.
To solve my problem what i did was:
1: uninstall , the current version of the mingw compiler , because i felt as though the one i had was corrupt in a way.
2:Redownloaded it the compiler from the website http://www.mingw.org/
3: set up the new Environmental variable where i save it , witch was C:\MinGW\bin
I had to install g++ from the command line(cmd ,command prompt)
by using this command mingw-get install g++witch is located inside bin on default
now i created one more directory in the environmental variables , C:\MinGW\bin\g++.exe
6.Now everything works , and is normal
If you are trying to run the compiler from the command line then you have to put double quotes around the path, because the path contains two whitespaces (this is the reason for the first error).
The reason for second error is that you didn't specify which C++ program you want to compile. You have to append the filename of your C++ input file to your command:
C:\Users\Kxrk>"C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe" program.cpp
See Barmak Shemiranis answer if don't want to enter the full path all the time. After that you can just use this:
C:\Users\Kxrk>g++ program.cpp
You have to use quotation marks around the path so that is treated as a single path:
c:\>"c:\program files\path\g++.exe"
A better way is to set the environment variables. Open Environment variables windows (in Windows 10 you can type in "environment variables" in search box) or right click on "Computer" in desktop, open "Advanced System Settings" and find the button for "Environment variables"
Go to your command propmpt, type set path, it will show list of directories, copy them,
Now type set path=<data you copied> and then add a semicolon and possible directory to g++ usually C:\MinGW\bin
So I have started to use Sublime Text 3 recently with my Ubuntu OS. I wanted to test it out so wrote a simple piece of c++ code. But when I try to build it does nothing, I have checked online and still nothing I even installed a build system (https://github.com/shikharkunal99/Sublime-Build-System) and still whenever I go to build it just opens open a black section at the bottom (see picture)
Install g++ to run c++ code
apt-get install g++
Then I will tell you a personal trick that I used. it is:
find | grep "part of your filename"
Replace "part of your filename" section with the name of the file or a part of the name of the file.
Suppose, the file name is Here.c. I type "Here" in place of part of your filename.
Then the final step, type
./a.out
Output is ready in front of you.
This post will help you in setting up Sublime Text 3 in a way that leads to a good workflow specifically for C++ programming environment (Ubuntu, GNU C++ Compiler) :
Note: Only the following step is essential for running c++ programs.
1. Create a Build System in Sublime Editor :
Sublime Text provides build systems to allow users to run external programs.
Go to Tools -> Build System -> New Build System.
Paste the following code in the file
{
"cmd": ["g++ -Wall -Wextra -O2 -pthread -H -std=c++17 \"${file}\" -o runfile && ./runfile <input.in> output.out"],
//above line works fine if input.in and output.out files are present in same directory in which .cpp file is present else add complete address of these files for using them as common input output files in your system.
"shell":true,
"working_dir":"$file_path",
"selector":"source.c,source.c++,source.cpp",
"variants": [
{
"name": "Variant Run",
"cmd" : ["gnome-terminal -- bash -c \"g++ $file_name ;echo ------------Output-------------; ./a.out;echo;echo; echo Press ENTER to continue; read line;exit; exec bash\""
],
}
]
}
Save the file (By default the file is placed in "~/.config/sublime-text-3/Packages/User" dir) something like "C++17.sublime-build" to differentiate it from the other build system files.
Create input.in and output.out text files in your working directory. This can be used for piping input from the input.in file, and output to the output.out file.
Note in the first line it uses the -std=c++17 flag to enable the latest features of C++17. If you don't want this or want to use C++14, replace this with the -std=c++14 flag.
Refer to https://linux.die.net/man/1/g++ for different compiler flags.
See Also https://discuss.codechef.com/t/are-any-compiler-flags-set-on-the-online-judge/1866
2. Setup window layout :
Create three new c++ file, file.cpp. Select View > Layout > Columns : 3. This will create three columns in the workspace. Select View > Groups > Max Columns : 2.
Write a hello world program & save inputs if any in the input.in file, and test its working. Use Shift+Ctrl+B and Select C++17 to build and execute the file (If selected C++17 - Variant Run it will execute the program in a separate terminal window like a normal program would).
The windows will look like this when you are done.
Layout Preview
3. Precompile headers :
Generally useful in competitive programming, we can speed up compilation time by precompiling all the header files as mentioned here, i.e. by precompiling the bits/stdc++.h header file.
For this, first, navigate to the stdc++.h file. This will be located at a directory similar to ~/usr/include/x86_64-linux-gnu/c++/9/bits Open terminal window here.
Run the command sudo g++ -std=c++17 stdc++.h, to compile the header. Take care to use the same flags you used in your build system. Check to make sure that the stdc++.h.gch file was created in that directory.
4. Sublime Text features :
Snippets & Completion
Read up on the documentation of snippets and completions at the official guide.
5. Other Features :
Read https://scotch.io/bar-talk/best-of-sublime-text-3-features-plugins-and-settings
This program works perfectly fine for me using Build 3120, and I expect it will work fine with previous builds. First, you need to select Tools → Build System → C++ Single File (Tools → Build System → Automatic should also work, but I prefer to be explicit). Then, either hit CtrlShiftB or select Tools → Build With… and select C++ Single File - Run. This will compile your .cpp file to an executable in the same directory as the source file, then run it.
Well I also got various issues with this thing finally I got an amazing thing in the package control pallet.Follow the instructions:
1.Open up the Package control Pallet
2.Search for C++ Builder
3.You will see C++ Builder-Mingyang Yang
4.click it and then wait for a couple of seconds
5.finally go to tools->build system->select C++ Builder-Mingyang Yang
6.finally tap the Shift+Ctrl+B and then select C++ Builder-Mingyang Yang Build and Run
7.finally here you go you can not only build this but also use the console for input
Note:This will execute only when there is gcc compiler included in the terminal otherwise at first install gcc by the command apt-get install gcc then you can use c++
I would like to have a variable (or #define) in C++ source that will increment each time I use Qt Creator to build source code. Is there any way I can do this, perhaps some Qt Creator plugin or similar? If there is a way to do it if I use "make" on command line to build?
In your .pro file, you can create a variable that contains the results of a command-line program. You can then use that to create a define.
BUILDNO = $$(command_to_get_the_build_number)
DEFINES += BUILD=$${BUILDNO}
If you just want a simple incrementing number, you could use a pretty simple script:
#!/bin/bash
number=`cat build_number`
let number += 1
echo "$number" | tee build_number #<-- output and save the number back to file
I should note that this would cause the build number to increment every time you build, and also increment if you try to build but it fails. A better way is to get a build number based on the state of the code, and many version control tools can get you a text string for that, if not a number.
The Windows equivalent for Joerg Beutel's improved solution https://stackoverflow.com/a/5967447/1619432:
.pro:
build_nr.commands = build_inc.bat
build_nr.depends = FORCE
QMAKE_EXTRA_TARGETS += build_nr
PRE_TARGETDEPS += build_nr
HEADERS += build.h
build_inc.bat:
#echo off
set /p var= <build.txt
set /a var= %var%+1
echo %var% >build.txt
echo #define BUILD %var% >build.h
echo %var%
Usage
#include "build.h"
...
qDebug() << "Build number:" << BUILD;
As I wrote before after some testing I found that the original solution has a problem since the version number is not updated every time a new build is done. In a lot of cases I had edited a source file, run the build, but still got the same build number ... The building process just decided that nothing was changed and skipped the step which would have updated the build number. I first attempted to find a way to force that step, but couldn't figure it out. Finally I decided to go a different way. Now I use the script to generate a header file
build_number.h which contains a #define BUILD with the updated number behind. So Calebs script is now a bit modified (build_number.sh) :
#!/bin/bash
number=`cat build_number`
let number++
echo "$number" | tee build_number #<-- output and save the number back to file
echo "#define BUILD ""$number" | tee ../MyProject/build_number.h
The incrementing number is still stored within a file called build_number. I could have avoided a third file by parsing the generated header-file for the number, but decided against it. Note that the script and the generated header are located in the projects directory while the build_number file is in the build directory. That's not perfect, but I can live with it.
In order to put things together there are now some more things to do. First the generated header-file needs to be added to the project in the Qt Designer ... Right-click on Header-Files and "Add existing file". Second, it has to be included in the C++-file where the BUILD define inside is accessed ... #include "build_number.h" ... and last but not least some additions have to be made to the project file (MyProject.pro). Note that I deleted the stuff from Calebs solution, so we start from scratch here :
build_nr.commands = ../MyProject/build_number.sh
build_nr.depends = FORCE
QMAKE_EXTRA_TARGETS += build_nr
PRE_TARGETDEPS += build_nr
These lines (I put them before the HEADERS section) force the execution of the script, which reads the last build number from build_number, increments it, writes it back and also generates an updated version of the build_number.h file. Since that's part of the source of the project the new value gets linked into the code every time.
There's one thing to mention - now the building process is never at the opinion that nothing has changed. So even if you leave your code unchanged a new run of make will generate a new version number and build a new binary. The old solution left the number when code changed, this new solution forces a new build even when the source is unchanged, since I force a change in that one header file. One would have prefered something in between but since the header is only included in one place the rebuild is very fast and doesn't hurt much. But still, if somebody knows how to get the best of both worlds please advise. At least now I'll not have two different binaries with the same version number.
Caleb's suggestion is great, but didn't work "out of the box" in my case. I got some errors instead and it took some reading to fix them. The changes are very minor. I was using Qt 4.7 on Ubuntu Linux ... The first change, if you can believe it, was in the shell script to go from let number += 1 to let number++ ... I normally use/program Windoze, so I can't explain that, but when I run the script from a command line (shell prompt) in the original case I get errors reported, in the changed case all goes well and incrementing numbers are returned ...
Since it's not completely reported by Caleb - I used build_number.sh as the name of the shell script and made another file with the name build_number (without .sh) and put just a zero inside, nothing else.
The last and most obnoxious bug was fixed by replacing BUILDNO = $$(command_to_get_the_build_number) with BUILDNO = $$system(./build_number.sh) in the Qt project file. Note the system after $$ and the required ./ in front of the file name. The later is elementary for a regular Linux user, but not as much so for a Windows user.
Hope this makes it more straight forward for people new to all this, like myself. You can read more in the Qt Designer Help section if you seek for qmake, including the function reference, Advanced Use etc.
Oh, one last word ... I also had to change DEFINES += -DBUILD=$${BUILDNO} to DEFINES += BUILD=$${BUILDNO}, so the -D is gone. Inside your C++ code you would use BUILD as if you had written #define BUILD 1234 at the top of your file.
Here's a solution for Win7 I came up with based on handle's solution.
This solution also makes Windows give yer version # when you right-click yer target, and choose Properties | Details. It works in Win7, and probably most earlier versions.
Ok, you make yer build_inc.bat:
#echo off
copy /b myapp.rc +,,
set /p var= <build.txt
set /a var= %var%+1
echo %var% >build.txt
echo #define BUILD %var% >build.h
and put it in yer proj folder. (copy /b myapp.rc +,, is inscrutable Microsoft-eese for "touch" - to update a file's time-stamp.) So far, so good - so what?!!
This part is optional, if you don't need the version encoded into the binary. Create a .rc file, e.g.:
#include "build.h"
1 VERSIONINFO
FILEFLAGS 32
FILEVERSION 1, 0, BUILD, 0
PRODUCTVERSION 1, 0, BUILD, 0
FILEOS 4
FILETYPE 1
{
BLOCK "StringFileInfo"
{
BLOCK "040904B0"
{
VALUE "FileDescription", "program"
VALUE "OriginalFilename", "program.exe"
VALUE "CompanyName", "you"
VALUE "FileVersion", "Release"
VALUE "LegalCopyright", "Copyright (c) 2016, you, fool!"
VALUE "ProductName", "Yer proggie"
VALUE "ProductVersion", "Release"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x0409, 0x04B0
}
}
A more full-blown version is available here: Versioning DLLs. BTW: It won't work without the VarFileInfo block. This .rc is used for stuff like right-clicking and getting this info in Properties | Details. I have both a M$ .rc file for this info and the app icon, and add other resources in Qt Creator under Resources.
Not so optional: Here's the part I've spent some time hacking to find. In Qt Creator, with yer proj opened, click the little computer icon and put it in release mode. Click on "Projects". Click on "Add Build Step", choose Custom Process Step, and click the hat icon "^" until it is at the top of the list. Say you've named yer .rc, "myapp.rc". Make tha build step read as follows:
Command: cmd.exe
Arguments:/c build_inc.bat
Working Directory: %{CurrentProject:Path}
While a qmake-based version might work well from the command line or command line tools called from an IDE, in Qt Creator, the build steps are preferable, I believe. Qt Creator doesn't actually run qmake for each build; but build steps are run every build.
Now, add this to yer .pro file:
RC_FILE += myapp.rc
Also, add myapp.rc to yer proj. It'll show up under "Other Files".
Now rebuild. Every rebuild will trigger a touch of the resource file, thereby running "rc" every time. Otherwise, the build number won't get encoded into the binary right. It runs quickly for me. Every rebuild will increment this number. I've only bothered to add them to the "Release" build; so debug builds don't increment this. They'll just use the number of the last build. You will need to run it once in release to avoid an error, I believe. This works without separately re-running qmake each time in Qt Creator; and gives you a different build number each time. It doesn't trigger any other recompiles. You have the overhead of running "rc" and linking each time, as opposed to doing nothing if everything is up to date; but OTOH, I do it for release builds only; you almost always link for a build or run anyway; and again, "rc" is fast.
Optional: You can move the BUILD preprocessor symbol wherever you want in yer vers. #. (Note: You can also add yer app icon with something like this:
IDI_ICON1 ICON DISCARDABLE "Icons/myicon.ico"
This makes it show up in Explorer even before the file is run.)
You can also add "build.h" to yer proj formally in Qt Creator, include it in a file you want to use the build # in, and use it as a string, e.g. with:
#include <QDebug>
#include "build.h"
#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)
qDebug() << QString("(build ")+STR(BUILD)+")";
I just noticed a side effect: If you do it this way, it will rebuild before every run in Release. I guess that's not too bad a price to pay. I guess I can always copy the runtimes into the release directory, and run it from Explorer; or just put up with the extra compile of my about.h, the run of "rc" and the link with each run in release. For that matter, I could just create an external tool to run it with a keyboard shortcut. I'm certainly open to any improvements on this. For the time being, I'm not bothering, as just compiling "about.cpp", running "rc" and linking with every run doesn't take very long. Still, people: automatic build numbers!
☮!
Edit: Optional: In order to get it to increment the build number only when you build or rebuild your project, but not when you run it (even though a build will always occur in Release), go to Projects | Build and Run | Run, click "Add a Deploy Step" and choose "Custom Process Step":
Command: cmd.exe
Arguments: /c if exist build.old copy /y build.old build.txt
Working Directory: %{CurrentProject:Path}
Then, add
copy /y build.txt build.old
after #echo off in the .bat file. It is even possible, although involved, to make custom new project templates: Extending Qt Creator Manual
Edit: I've now made it work with one, not two, custom build steps.