When I compile the code below, I got these error messages:
(Error 1 error C2065: 'M_PI' : undeclared identifier
2 IntelliSense: identifier "M_PI" is undefined)
What is this?
#include <iostream>
#include <math.h>
using namespace std;
double my_sqrt1( double n );`enter code here`
int main() {
double k[5] = {-100, -10, -1, 10, 100};
int i;
for ( i = 0; i < 5; i++ ) {
double val = M_PI * pow( 10.0, k[i] );
cout << "n: "
<< val
<< "\tmysqrt: "
<< my_sqrt1(val)
<< "\tsqrt: "
<< sqrt(val)
<< endl;
}
return 0;
}
double my_sqrt1( double n ) {
int i;
double x = 1;
for ( i = 0; i < 10; i++ ) {
x = ( x + n / x ) / 2;
}
return x;
}
It sounds like you're using MS stuff, according to their docs
Math Constants are not defined in Standard C/C++. To use them, you must first define _USE_MATH_DEFINES and then include cmath or math.h.
So you need something like
#define _USE_MATH_DEFINES
#include <cmath>
as a header.
math.h does not define M_PI by default.
So go with this:
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
This will handle both cases either your header have M_PI defined or not.
M_PI is supported by GCC too, but you've to do some work to get it
#undef __STRICT_ANSI__
#include <cmath>
or if you don't like to pollute your source file, then do
g++ -U__STRICT_ANSI__ <other options>
As noted by shep above you need something like
#define _USE_MATH_DEFINES
#include <cmath>
However you also include iostream.
iostream includes a lot of stuff and one of those things eventually includes cmath. This means that by the time you include it in your file all the symbols have already been defined so it is effectively ignored when you include it and the #define _USE_MATH_DEFINES doesn't work
If you include cmath before iostream it should give you the higher precision constants like M_PI
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
Use this include for Windows 10 (and Windows 11):
#include <corecrt_math_defines.h>
I used C99 in NetBeans with remote linux host with its build tools.
Try adding #define _GNU_SOURCE and add the -lm during linking.
You must use _USE_MATH_DEFINES before other headers like this:
#define _USE_MATH_DEFINES
#include <cmath>
#incude other headers...
Related
I'm using boost::uuids inside maps (labeled_graph, actually), so I need a properly working operator <. Unfortunately it isn't, if BOOST_UUID_USE_SSE2 is enabled (and thus, uuid_x86.hpp is used).
Here is example code:
#include <boost/uuid/nil_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <string>
#include <sstream>
#include <iostream>
#include <assert.h>
#define CHECK(x) do { if(x) { std::cout << #x << "\n"; } } while(0)
static inline boost::uuids::uuid StringToUuid(const std::string &str)
{
boost::uuids::uuid u = boost::uuids::nil_uuid();
std::stringstream uuidstring(str);
uuidstring >> u;
return u;
}
int main() {
boost::uuids::uuid vmi_uuid = StringToUuid("00000000-0000-0000-0000-000000000001");
boost::uuids::uuid vmi2_uuid = StringToUuid("00000000-0000-0000-0000-000000000002");
CHECK(vmi_uuid != vmi2_uuid);
CHECK(vmi_uuid < vmi2_uuid);
CHECK(vmi2_uuid < vmi_uuid);
return 0;
}
When uuid_x86.hpp is used, operator< is incosistent -- returns false in both cases:
vmi_uuid != vmi2_uuid
Disabling intrinsic-based header returns things back to normal:
vmi_uuid != vmi2_uuid
vmi_uuid < vmi2_uuid
This is reproducable only with special UUIDs (1 and 2), having totally random ids doesn't reveal this problem.
I have Ubuntu Xenial with libboost 1.58. CPU is i7-6600U if it matters.
Am I missing something?
I work with VC++6 and I want to use complex power function (pow()) in one of my self-made function.
I wrote my necessary functions in a header file (.h).
Here is my function in the header file:
#include "MrServers/MrVista/Ice/IceIdeaFunctors/DllInterface.h"
// Base class:
#include "MrServers/MrVista/Include/Ice/IceUtils/IceImageReconFunctors.h"
#include "MrServers/MrVista/Include/Ice/IceUtils/IceUtils.h"
#include "MrServers/MrVista/Include/Ice/IceAlgos/IceWrapper.h"
// C++ class:
#include <vector>
#include <iostream>
#include <math.h>
#include <cmath>
#include <numeric>
#include <complex>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
// #define ACC 40.0 //Make larger to increase accuracy.
// #define BIGNO 1.0e10
// #define BIGNI 1.0e-10
// #define PI 3.14159265
typedef std::vector <float> array_1d;
typedef std::vector <array_1d> array_2d;
typedef std::vector <array_2d> array_3d;
using namespace std;
IceWrapper myice;
...other function...
void Hankel_Transform(IceAs& dstAs, IceAs& srcAs, int M, int N, int nCha, int nPHS, float delta_r, float delta_rho, int r_range)
{
//parameters for Hankel Transform
//M: Number of samples on a spoke
//N: total number of orders
//rho: a 1D vector contains rho values (in source image)
//r: a 1D vector contains r values (for final image)
//r_range: length of vector r
double res = 0.005;
int z_ord = (int) N/2;
float pii = 3.14159265f; // f means float. to avoid error
array_3d bessel_table(N, array_2d(M, array_1d(r_range)));
// load "bessel_table" from PDS// (will be added later)
// load bessel_table
//array_2d bessel_table;
//bessel_table = read_bessel_txt();
// create pointer in order to access srcAs and dstAs
CMPLX *p_srcAs = (CMPLX*) srcAs.calcSplObjStartAddr();
CMPLX *p_dstAs = (CMPLX*) dstAs.calcSplObjStartAddr();
// Hankel Formula //
//int my_ind;
float my_j;
float r;
float rho;
complex<float> temp (0.0 , 0.0);
complex<float> fn_r (0.0 , 0.0);
complex<float> immm(0, 1);
float ipow =0.0f;
//CMPLX *temp;
//CMPLX *fn_r;
for (int phase = 0; phase < nPHS; phase++)
{ for(int ord = -(N/2); ord < (N/2); ord++) //lines
{ for(int nc = 0; nc < nCha; nc++) //channels
{ for(int rr = 0; rr < r_range; rr++) //columns
{
r=(float)(rr+1)*delta_r;
fn_r=complex<float>(0.0 , 0.0);
//fn_r -> re = 0;
//fn_r -> im = 0;
for(int rhoo = 0; rhoo < M; rhoo++)
{
rho = delta_rho/2 + (float)rhoo*delta_rho;
// to avoid redunduncy in calculation of besselj in cha and phase
if ( nc == 0 && phase == 0 )
{
my_j = bessj(ord , (float)(pii*rho*r));
bessel_table[ord+z_ord][rhoo][rr] = my_j;
}
else
{
my_j = bessel_table[ord+z_ord][rhoo][rr];
}
//my_ind = (int)floor((float)(pii*rho*r/res)); // should be "round" :(
//if(my_ind==0){my_ind=1;}
//my_j = bessel_table[ord+z_ord][my_ind-1]; // dar c++ andis ha az 0 shoru mishe!!
// bayad esme jadval "bessel_table" bashad!
temp = complex<float>(rho*my_j*p_srcAs->re , rho*my_j*p_srcAs->im);
fn_r += temp;
p_srcAs++;
}
ipow = (float)ord;
//ICE_OUT(std::pow<complex>(fn_r,2));
fn_r *= std::pow(immm,ipow); //exp(ipow*log(immm));//pow(immm,ipow);
p_dstAs->re = real(fn_r);
p_dstAs->im = imag(fn_r);
p_dstAs++;
if(rr != (r_range-1) )
{
p_srcAs -= M;
}
}
}
}
}
}
Without putting this line: fn_r *= std::pow(immm,ipow) , everything works fine and the project correctly compiles. But when i try to put this line, or using exp() or log() function compiling fails with this errors:
IcePFTd_HankelFunctor.obj : error LNK2001: unresolved external symbol "struct _STL::complex<float> __cdecl _STL::pow(str
uct _STL::complex<float> const &,float const &)" (?pow#_STL##YA?AU?$complex#M#1#ABU21#ABM#Z)
/n4/x86/prod/bin/IcePFTd.dll : fatal error LNK1120: 1 unresolved externals
make: *** [\n4\x86\prod/bin/IcePFTd.dll] Error 96
I also tried to use the expression exp(ipow*log(immm)) instead of power function, but it also fails with the same error.
I tried to use this function (pow()) in a simple code in visual studio 2016,it works fine and it's just okay to consider #include <complex> in the first lines of the header.
Do you have any idea?
Any help will be appreciated.
essentially I'm writing a short script. The easiest way to look at is that it's for a game with a resource collection. ResGain is the resources gained, and BonusGain is the chance to earn an extra resource. I am getting Identifier not found errors for the ResGain and Bonus Gain functions, but I have declared the ResGain and BonusGain functions before main. Any ideas why?
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
float ResGain(float u, int r) //calc Base resource Gain
{
float lapout;
lapout = r * u;
return (lapout);
}
char BonusGain(int b) //Determines if a bonus material would be produced.
{
char bonus;
int rng;
rng = rand() % 100 + 1;
if (rng <= b)
bonus = 1;
return(bonus);
}
int main()
{
float l;
l = ResGain(1.1,70);
cout << "You have earned" << l << "Lapis";
if (BonusGain(3)==1)
cout << "You have also earned a bonus material";
system("pause");
return 0;
}
Most probably the identifier not found is system() which is not part of the standard library. You should locate the Windows-specific header where it is declared.
Global.h
#ifndef GLOBAL_H
# define GLOBAL_H
#define DEBUG
#ifdef DEBUG
# define IF_DEBUG( ... ) __VA_ARGS__
#else
# define IF_DEBUG( ... )
#endif /* DEBUG */
#endif /* GLOBAL_H */
Main.cpp
#include <string>
#include <iostream>
#include "Global.h"
int main() {
int A = 1;
int B = 2;
int C = 0;
IF_DEBUG(
std::cout << "\nStep 1> Calculating...\n";
)
C = A + B;
// DO WHATEVER
IF_DEBUG(
std::cout << "\nStep n> ...\n";
)
// ...
std::cout << C << std::endl;
// Note: I could also do some operations within the IF_DEBUG macro.
IF_DEBUG(
int X = 10;
int Y = 5;
int Z = X / Y;
std::cout << Z << std::endl;
)
IF_DEBUG(
std::cout << "\nDebugged! This program has been paused. Enter any key to continue!\n";
::getchar();
)
return 0;
}
Do you see how I defined IF_DEBUG in the Global header file (Global.h) and how I constantly used
it in the Main source file (Main.cpp) for debugging purposes?
Is it okay and safe to do that?
I am asking this question because I am unsure if its okay to do that. When I show this to my friend and he said its "bad" to do that. Therefore, I am unsure.
This is a very common and useful trick. But it's better not to have the #define DEBUG in the source code. You can define it in the compile command line instead. g++ -DDEBUG -c file.cpp will compile the code as if DEBUG was defined.
If you're using a Makefile you can add it to the CPPFLAGS (C Preprocessor Flags) variable: CPPFLAGS=-DDEBUG.
If you're using an IDE try to find the C Preprocessor Flags in the project settings.
These functions are Utility type things that most of my programs objects will use. I want to have them in a namespace and have them global. This namespace is defined in a header and then added to my precompiled header. However so far I have used the function from this namespace in 2 different objects and the compiler is throwing the multiply defined symbols error on these 2 objects.
namespace file
#ifndef UTILS_H
#define UTILS_H
#include <random>
#include <cmath>
namespace Utils
{
extern int GetRandomBetween(int low, int high)
{
if (low < 0 || low >= high)
return 0;
int seed = high - low;
return (rand() % seed) + low;
}
};
#endif
and my precomp header
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
//#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include <random>
#define SAFE_DELETE( p ) { if( p ) { delete ( p ); ( p ) = NULL; } }
#define SAFE_DELETE_ARRAY( p ) { if( p ) { delete[] ( p ); ( p ) = NULL; } }
#define SAFE_RELEASE( p ) { if( p ) { ( p )->Release(); ( p ) = NULL; } }
// TODO: reference additional headers your program requires here
#include "Utils.h"
#include "Manager.h" // this object uses utils
#include "Bot.h" // this object uses utils
#include "LinkedList.h"
#include "Village.h" // this object will use utils in the future
The linker error message:
Manager.obj : error LNK2005: "int __cdecl Utils::GetRandomBetween(int,int)" (?GetRandomBetween#Utils##YAHHH#Z) already defined in Bot.obj
stdafx.obj : error LNK2005: "int __cdecl Utils::GetRandomBetween(int,int)" (?GetRandomBetween#Utils##YAHHH#Z) already defined in Bot.obj
c:\users\lee\documents\visual studio 2010\Projects\AI\Debug\AI.exe : fatal error LNK1169: one or more multiply defined symbols found
it also maybe worth noting that in my Manager class header I forward declared Bot. Same with Village class header.
Your function definition (ie: the source code) should not be in a header. The reason you are getting multiple definitions is that extern cannot convert a function definition (the source code) into a function declaration (ie: just the prototype). So you need to do this:
Util.h:
namespace Utils
{
int GetRandomBetween(int low, int high);
};
SomeSourceFile.cpp (probably Util.cpp):
namespace Utils
{
int GetRandomBetween(int low, int high);
{
if (low < 0 || low >= high)
return 0;
int seed = high - low;
return (rand() % seed) + low;
}
};
Alternatively, you can declare the function inline in the header:
namespace Utils
{
inline int GetRandomBetween(int low, int high)
{
if (low < 0 || low >= high)
return 0;
int seed = high - low;
return (rand() % seed) + low;
}
};
Though you should only use this for small functions.
Manager.cpp and Bot.cpp both include Util.h
Because of this, when they are compiled, both object files export the symbol "GetRandomBetween". When the linker goes to combine these object files into an executable, it finds 2 instances of the function. The linker can't determine which one to use (and it doesn't understand that they are identical).
If you want to make the object files NOT export the symbol (so that you dont have a linker conflict), remove the extern keyword.