Standard compliant C++ compilers define a __cplusplus
macro which may
be inspected during preprocessing to determine under what standard a
file is being compiled, e.g:
#if __cplusplus < 201103L
#error "You need a C++11 compliant compiler."
#endif
#include <iostream>
#include <vector>
int main(){
std::vector<int> v {1, 2, 3};
for (auto i : v){
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
My question is:
- Is there a standard way to indicate what standard a source file should be compiled with?
That would allow build tools to inspect sources prior to compilation
to determine the appropriate argument for -std=
(cf. shebang's which
can indicate scripting language/version: #!/usr/bin/env python3
).
A non standard and brittle way I can think of is looking for the
preprocessor checks of __cplusplus
but in the example above I could
also have written:
#if __cplusplus <= 199711L
#error "You need a C++11 compliant compiler."
#endif
hence, writing e.g. a regex would become quite tricky to catch all variations.
EDIT:
While I sympathize with the answer by @Gary which suggests relying on a build system, it assumes that we actually will have a build step.
But you can already today:
- use an interpreter to run a C++ program using e.g. CINT
- or use a source to source translation using e.g. rosecompiler
My question is also about indicating that the source is C++ and what version it was intended for (imagine someone digging out my code 70 years from now when C++ might be as popular as say Cobol is today).
I guess the equivalent thing I would be looking for is the C++ equiavlent of HTML's:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
std=
get changed to that for this file? If not, then this approach makes no sense IMHO, at the project level decide which version you are using, and possibly have a check in the file for handling older compilers (to reject if it's too old...)-std=c++11
but strictly speaking the C++11 standard has some backward incompatible changes. And in general I think it's good as documentation (e.g. C++ headers often end with '.h' so there may be some confusion with C headers unless you inspect them manually)