问题
In Visual Studio 2012, I'm unable to declare certain names as global identifiers because they're already declared in math.h. Legacy issues makes it inconvenient for me to rename the identifiers in the source code. What are the options besides renaming?
#include "stdafx.h"
// iostream includes math.h which declares the following
_CRT_NONSTDC_DEPRECATE(_y1) _CRTIMP double __cdecl y1(_In_ double _X);
int y1; // error - y1 is already declared
void Main()
{
return;
}
Bonus question: Is Visual Studio 2012 handling this in a conforming manner?
回答1:
Since this is C++, you should use a namespace for your own stuff, especially if you have global variables.
#include "stdafx.h"
namespace MyApp
{
int y1; // MyApp::y1
}
This way, you can rely on the using keyword, where you need to use your y1
variable without the namespace name:
using MyApp::y1; // Now also y1
回答2:
The identifier y1
may appear in some versions of <math.h>
, but it's not defined by the C or C++ standard. You should be able to invoke the compiler in a way that avoids declaring y1
, perhaps by disabling language extensions. If the compiler doesn't let you do this, that's a bug in the implementation.
y1()
is one of the "Bessel functions of the second kind" (I'm not quite sure what that means). It's specified by POSIX.
回答3:
As I stated in my comments, iostream
will not be including math.h
, but rather cmath
. The subtle difference is that cmath
places everything in the std
namespace. The problem is that you're doing something as follows...
using namespace std;
... don't. As you can see, you are yourself introducing an ambiguity in the global namespace. Instead, try to explicitly specify what you need from std
, rather than polluting the global namespace with whatever std
members have been declared in your included headers. You should also stray from using global variables and the global namespace itself.
As a side note, try to show whole code, since it was unclear that _tmain
had called Main
here.
来源:https://stackoverflow.com/questions/12443595/how-to-deal-with-math-h-pollution-in-visual-studio-c