问题
I have included a unix timestamp __DATE__ in one of my cpp source files to indicate the build date of my program. Naturally with default setups it compiles the file only when I change it but now I'd like to have it always compiled. I tried to search through the project settings but it seems that this would need deeper understanding of the compiler. I'm using Eclipse with g++.
I tried to google and search for an answer but I found it difficult to find good keywords for this.
Also is there a markable difference wether I do this change for a header file instead of the source file?
Thanks for the answers.
回答1:
You may create a 'pre-build' step which touch the file (so the time stamp is modified and force to recompile the file).
回答2:
it seems that this would need deeper understanding of the compiler.
No, it must be done by the build system.
A very simple-minded way of doing it is as follows. Create a single file called date.cpp with the following content and nothing else:
#include <string>
std::string build_time() {
return __DATE__ " " __TIME__;
}
You can use it like this in some other source file
cout << "Built on " << build_time() << endl;
The build system keeps track of your changes and it will only recompile those source files that have changed (that are necessary to be recompiled). Since you are not changing date.cpp file, it won't recompile it. However, you can force it by right clicking on the project folder and then
Properties > C/C++ Build > Settings > Build Steps > Post-build steps
and adding the following line to the comand field on Linux:
rm -f <path to the Debug / Release directory>/date.o
where you put yours to <path to the Debug / Release directory>.
On Windows del /q seems to do the same as rm -f, please check.
Since we delete the generated object file date.o, the build system must rebuild it again with the current build date and time when you compile the your application.
It's likely that there are many other variants but the above is in my opinion simple enough and does the trick.
来源:https://stackoverflow.com/questions/21086869/how-to-always-compile-a-cpp-file-with-eclipse