Unresolved External symbol, C++, VS 2015 [duplicate] - c++

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
I have read the model answer on unresolved externals and found it to be incredibly useful and have got it down to just these last two stubborn errors which are beyond me.
I've attached all the code just in case, if you would like to see the headers or anything else please say.
// Stokes theory calculations
#include <math.h>
#include <stdio.h>
#include <process.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#define ANSI
#include "../Allocation.h"
#define Main
#define Char char
#define Int int
#define Double double
#include "../Allocation.h"
#include "../Headers.h"
Double
kH, skd, ckd, tkd, SU;
Double
ss[6], t[6], C[6], D[6], E[6], e[6];
// Main program
int main(void)
{
int i, Read_data(void), iter, Iter_limit = 40;
double F(double), kd1, kd2, kFM, omega, delta, accuracy = 1.e-6, F1, F2, Fd;
void CDE(double), AB(void), Output(void);
Input1 = fopen("../Data.dat", "r");
strcpy(Convergence_file, "../Convergence.dat");
strcpy(Points_file, "../Points.dat");
monitor = stdout;
strcpy(Theory, "Stokes");
strcpy(Diagname, "../Catalogue.res");
Read_data();
z = dvector(0, 2 * n + 10);
Y = dvector(0, n);
B = dvector(0, n);
coeff = dvector(0, n);
Tanh = dvector(0, n);
monitor = stdout;
H = MaxH;
iff(Case, Wavelength)
{
kd = 2. * pi / L;
kH = kd * H;
CDE(kd);
}
// If period is specified, solve dispersion relation using secant method
// Until February 2015 the bisection method was used for this.
// I found that in an extreme case (large current) the bracketting
// of the solution was not correct, and the program failed,
// without printing out a proper error message.
iff(Case, Period)
{
fprintf(monitor, "\n# Period has been specified.\n# Now solving for L/d iteratively, printing to check convergence\n\n");
omega = 2 * pi / T;
// Fenton & McKee for initial estimate
kFM = omega*omega*pow(1 / tanh(pow(omega, 1.5)), (2. / 3.));
kd1 = kFM;
kd2 = kFM*1.01;
CDE(kd2);
F2 = F(kd2);
for (iter = 1; iter <= Iter_limit; ++iter)
{
CDE(kd1);
F1 = F(kd1);
Fd = (F2 - F1) / (kd2 - kd1);
delta = F1 / Fd;
kd2 = kd1;
kd1 = kd1 - delta;
fprintf(monitor, "%8.4f\n", 2 * pi / kd1);
if (fabs(delta / kd1) < accuracy) break;
F2 = F1;
if (iter >= Iter_limit)
{
printf("\n\nSecant for solution of wavenumber has not converged");
printf("\nContact John Fenton johndfenton#gmail.com");
getch();
exit(1);
}
}
kd = kd1;
kH = kd * H;
}
z[1] = kd;
z[2] = kH;
SU = 0.5*kH / pow(kd, 3);
printf("\n# Stokes-Ursell no.: %7.3f", SU);
if (SU > 0.5)
printf(" > 1/2. Results are unreliable");
else
printf(" < 1/2, Stokes theory should be valid");
e[1] = 0.5 * kH;
for (i = 2; i <= n; i++) e[i] = e[i - 1] * e[1];
// Calculate coefficients
AB();
z[7] = C[0] + e[2] * C[2] + e[4] * C[4]; // ubar
z[8] = -e[2] * D[2] - e[4] * D[4];
z[9] = 0.5 * C[0] * C[0] + e[2] * E[2] + e[4] * E[4];
if (Current_criterion == 1)
{
z[5] = Current*sqrt(kd);
z[4] = z[7] + z[5];
z[6] = z[4] + z[8] / kd - z[7];
}
if (Current_criterion == 2)
{
z[6] = Current*sqrt(kd);
z[4] = z[6] - z[8] / kd + z[7];
z[5] = z[4] - z[7];
}
iff(Case, Wavelength) z[3] = 2 * pi / z[4];
iff(Case, Period) z[3] = T * sqrt(kd);
for (i = 1; i <= n; i++)
Tanh[i] = tanh(i*z[1]);
// Output results and picture of wave
Solution = fopen("Solution.res", "w");
Elevation = fopen("Surface.res", "w");
Flowfield = fopen("Flowfield.res", "w");
Output();
fflush(NULL);
printf("\nTouch key to continue "); getch();
printf("\n\nFinished\n");
}
I get these error messages:
LNK2019 unresolved external symbol "void __cdecl Output(void)" (?Output##YAXXZ) referenced in function _main Stokes
LNK2019 unresolved external symbol "double * __cdecl dvector(long,long)" (?dvector##YAPANJJ#Z) referenced in function _main Stokes
I have checked everything on the list given to try and find where these errors are coming from and have whittled it down to just these two left.
Things tried so far:
Checking basic syntax
Checking and ensuring correct headers are available
Looked at external dependencies (but i don't really know what i'm doing here)
Looked at the solutions tried here but none worked.
Any help would be greatly appreciated!

Unresolved External Symbols means that your code can't find the definition of the method or class you're trying to use. This usually means one (or more) of several things has happened:
You didn't point to the directory that contains the object library (.lib on Windows, .so on Linux) for the library you're using
You forgot to specify in the linker that you need to use the library in question (that list of kernel32.lib, user32.lib,... needs to include the name of the library you're using)
The library you're trying to use is meant to be linked statically and you're trying to link it dynamically (or vise-versa). Check the documentation for the library and make sure you're using the correct form. Some libraries expect extra #define statements to be included or omitted depending on whether you're linking statically or dynamically.
You changed build options and forgot to update the libraries in the other build options. If you're set to Release or x64, check to make sure that your build options are set correctly in all environments.
EDIT: I'll also corroborate what the others said in the original comment thread: make sure that the code that defines Output() and dvector() are being linked to by your code.
There's a few other options, but those are the big ones that happen most frequently.

Related

What's the difference between initializing a vector in Class Header or Class constructor body?

I encountered a strange behavior in my C++ program that I don't understand and I don't know how to search for more information. So I ask for advice here hoping someone might know.
I have a class Interface that has a 2 dimensional vector that I initialize in the header :
class Interface {
public:
// code...
const unsigned short int SIZE_X_ = 64;
const unsigned short int SIZE_Y_ = 32;
std::vector<std::vector<bool>> screen_memory_ =
std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
// code...
};
Here I expect that I have a SIZE_X_ x SIZE_Y_ vector filled with false booleans.
Later in my program I loop at a fixed rate like so :
void Emulator::loop() {
const milliseconds intervalPeriodMillis{static_cast<int>((1. / FREQ) * 1000)};
//Initialize the chrono timepoint & duration objects we'll be //using over & over inside our sleep loop
system_clock::time_point currentStartTime{system_clock::now()};
system_clock::time_point nextStartTime{currentStartTime};
while (!stop) {
currentStartTime = system_clock::now();
nextStartTime = currentStartTime + intervalPeriodMillis;
// ---- Stuff happens here ----
registers_->trigger_timers();
interface_->toogle_buzzer();
interface_->poll_events();
interface_->get_keys();
romParser_->step();
romParser_->decode();
// ---- ------------------ ----
stop = stop || interface_->requests_close();
std::this_thread::sleep_until(nextStartTime);
}
}
But then during the execution I get a segmentation fault
[1] 7585 segmentation fault (core dumped) ./CHIP8 coin.ch8
I checked with the debugger and some part of the screen_memory_ cannot be accessed anymore. And it seems to happen at random time.
But when I put the initialization of the vector in the constructor body like so :
Interface::Interface(const std::shared_ptr<reg::RegisterManager> & registers, bool hidden)
: registers_(registers) {
// code ...
screen_memory_ =
std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
// code ...
}
The segmentation fault doesn't happen anymore. So the solution is just to initialize the vector in the constructor body.
But why ? what is happening there ?
I don't understand what I did wrong, I'm sure someone knows.
Thanks for your help !
[Edit] I found the source of the bug (Or at least what to change so it doesnt give me a segfault anymore).
In my class Interface I use the SDL and SDL_audio libraries to create the display and the buzzer sound. Have a special look where I set the callback want_.callback, the callback Interface::forward_audio_callback and Interface::audio_callback. Here's the code :
// (c) 2021 Maxandre Ogeret
// Licensed under MIT License
#include "Interface.h"
Interface::Interface(const std::shared_ptr<reg::RegisterManager> & registers, bool hidden)
: registers_(registers) {
if (SDL_Init(SDL_INIT_AUDIO != 0) || SDL_Init(SDL_INIT_VIDEO) != 0) {
throw std::runtime_error("Unable to initialize rendering engine.");
}
want_.freq = SAMPLE_RATE;
want_.format = AUDIO_S16SYS;
want_.channels = 1;
want_.samples = 2048;
want_.callback = Interface::forward_audio_callback;
want_.userdata = &sound_userdata_;
if (SDL_OpenAudio(&want_, &have_) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to open audio: %s", SDL_GetError());
}
if (want_.format != have_.format) {
SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to get the desired AudioSpec");
}
window = SDL_CreateWindow("CHIP8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SIZE_X_ * SIZE_MULTIPLIER_, SIZE_Y_ * SIZE_MULTIPLIER_,
hidden ? SDL_WINDOW_HIDDEN : 0);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
bpp_ = SDL_GetWindowSurface(window)->format->BytesPerPixel;
SDL_Delay(1000);
// screen_memory_ = std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
}
Interface::~Interface() {
SDL_CloseAudio();
SDL_DestroyWindow(window);
SDL_Quit();
}
// code ...
void Interface::audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
audio_buffer_ = reinterpret_cast<Sint16 *>(raw_buffer);
sample_length_ = bytes / 2;
int & sample_nr(*(int *) user_data);
for (int i = 0; i < sample_length_; i++, sample_nr++) {
double time = (double) sample_nr / (double) SAMPLE_RATE;
audio_buffer_[i] = static_cast<Sint16>(
AMPLITUDE * (2 * (2 * floor(220.0f * time) - floor(2 * 220.0f * time)) + 1));
}
}
void Interface::forward_audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
static_cast<Interface *>(user_data)->audio_callback(user_data, raw_buffer, bytes);
}
}
In the function Interface::audio_callback, replacing the class variable assignation :
sample_length_ = bytes / 2;
By an int creation and assignation :
int sample_length = bytes / 2;
which gives :
void Interface::audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
audio_buffer_ = reinterpret_cast<Sint16 *>(raw_buffer);
int sample_length = bytes / 2;
int &sample_nr(*(int*)user_data);
for(int i = 0; i < sample_length; i++, sample_nr++)
{
double time = (double)sample_nr / (double)SAMPLE_RATE;
audio_buffer_[i] = (Sint16)(AMPLITUDE * sin(2.0f * M_PI * 441.0f * time)); // render 441 HZ sine wave
}
}
The class variable sample_length_ is defined and initialized as private in the header like so :
int sample_length_ = 0;
So I had an idea and I created the variable sample_length_ as public and it works ! So the problem was definitely a scope problem of the class variable sample_length_. But it doesn't explain why the segfault disappeared when I moved the init of some other variable in the class constructor... Did I hit some undefined behavior with my callback ?
Thanks for reading me !

visual studio 2017 LNK2019: unresolved external symbol In GoogleTestGoogleMock Project

I am a noobie with C++. My first learning project uses GoogleTest and GoolgleMock, but, of course, I am new to those also. I installed googletestmock.v.141 v101 via NuGet. My main app, AstronomyCalculations, builds and runs without a problem. My test app, GMock, throws three LNK2019 errors when I try to build it.
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: __cdecl easter::easter(void)" (??0easter##QEAA#XZ) referenced in function "private: virtual void __cdecl GET_THE_DATE_OF_EASTER_ShouldReturnDateOfEaster_Test::TestBody(void)" (?TestBody#GET_THE_DATE_OF_EASTER_ShouldReturnDateOfEaster_Test##EEAAXXZ) GMock D:\Dev\Projects\AstronomyCalculations\GMock\GMock.obj 1
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: __cdecl easter::~easter(void)" (??1easter##QEAA#XZ) referenced in function "private: virtual void __cdecl GET_THE_DATE_OF_EASTER_ShouldReturnDateOfEaster_Test::TestBody(void)" (?TestBody#GET_THE_DATE_OF_EASTER_ShouldReturnDateOfEaster_Test##EEAAXXZ) GMock D:\Dev\Projects\AstronomyCalculations\GMock\GMock.obj 1
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: struct tm __cdecl easter::get_easter_date(int)const " (?get_easter_date#easter##QEBA?AUtm##H#Z) referenced in function "private: virtual void __cdecl GET_THE_DATE_OF_EASTER_ShouldReturnDateOfEaster_Test::TestBody(void)" (?TestBody#GET_THE_DATE_OF_EASTER_ShouldReturnDateOfEaster_Test##EEAAXXZ) GMock D:\Dev\Projects\AstronomyCalculations\GMock\GMock.obj 1
// AstronomyCalculations.cpp
int main() {
return 0;
}
// Easter.h
#pragma once
#include <ctime>
#include <string>
class easter
{
public:
easter();
~easter();
tm get_easter_date(int easter_year) const;
};
// Easter.cpp
#include "Easter.h"
easter::easter()
{
}
easter::~easter()
= default;
tm easter::get_easter_date(const int easter_year) const
{
const auto a = easter_year % 19;
const auto b = easter_year / 100;
const auto c = easter_year % 100;
const auto d = b / 4;
const auto e = b % 4;
const auto f = (b + 8) / 25;
const auto g = (b - f + 1) / 3;
const auto h = ((19 * a) + b - d - g + 15) % 30;
const auto i = c / 4;
const auto k = c % 4;
const auto l = (32 + (2 * e) + (2 * i) - h - k) % 7;
const auto m = (a + (11 * h) + (22 * l)) / 451;
const auto easter_month = (h + l - (7 * m) + 114) / 31;
const auto easter_day = ((h + l - (7 * m) + 114) % 31) + 1;
auto date_string = std::to_string(easter_year) +
"-" +
std::to_string(easter_month) +
"-" +
std::to_string(easter_day) +
" 00:00:00";
char date[20]; //a 1 char space for null is also required
strcpy_s(date, date_string.c_str());
tm ltm{};
char seps[] = " -:";
char *next_token = nullptr;
auto token = strtok_s(date, seps, &next_token);
ltm.tm_year = strtol(token, nullptr, 10);
token = strtok_s(nullptr, seps, &next_token);
ltm.tm_mon = strtol(token, nullptr, 10);
token = strtok_s(nullptr, seps, &next_token);
ltm.tm_mday = strtol(token, nullptr, 10);
token = strtok_s(nullptr, seps, &next_token);
ltm.tm_hour = strtol(token, nullptr, 10);
token = strtok_s(nullptr, seps, &next_token);
ltm.tm_min = strtol(token, nullptr, 10);
token = strtok_s(nullptr, seps, &next_token);
ltm.tm_sec = strtol(token, nullptr, 10);
ltm.tm_wday = 0;
return ltm;
}
// GMock.cpp
#include "stdafx.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "Easter.h"
int main(int argc, char** argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
TEST(GET_THE_DATE_OF_EASTER, ShouldReturnDateOfEaster)
{
easter estr;
const auto result = estr.get_easter_date(2000);
ASSERT_EQ(result.tm_year, 2000);
}
The linker seems unable to find the functions easter::easter(void), easter::~easter(void), and easter::get_easter_date(int)const
You are obviously including easter.h (and have it in your search path, or the compiler would have complained) but are you actually compiling easter.cpp or a mock object of it? (As far as I can tell from your sourcecode you are not actually mocking the class either). The header file is enough to satisfy the compiler, but when the linker tries to put the application together and realizes it is missing the object file, it balks - throwing LNK2019.
I can only strongly reccommend you look deeper into the documentation available for gtest & gmock.
In addition, you may also reconsider your naming schemes - Class types usually begin with an uppercase (i.e. Easter, not easter) to better tell them from variable names (which begin with lowercase). Also don't call your variables a, b, c, d - const auto a and its ilk are horrible to read, debug, and you will curse yourself I you ever find yourself in the postion of having to revisit the code after some weeks. Even if this were only some practice project, please also practice using good coding standards & naming conventions, so you (automatically) use them on bigger projects.
I finally solved this when I discovered that GoogleTest can be added in Visual Studio 2017 as a new project. Of course, I had to remove my original test project first and then add the new test project. It all worked out in the end, but, of course, I have no idea of why the link errors showed up in my original testing project; other than CharonX's insights.

Error C2668: 'boost::bind' : ambiguous call to overloaded function

I am trying to build Quantlib on VS2013 in the Release x64 mode.
I added the Boost libraries using Property Manager and then Went to solutions explorer and clicked on Build.
The final output was: Build: 18 succeeded, 1 failed. 0 up-to-date, 0 skipped.
When I double clicked on the error this file opened up (convolvedstudentt.cpp)
Copyright (C) 2014 Jose Aparicio
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev#lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ql/experimental/math/convolvedstudentt.hpp>
#include <ql/errors.hpp>
#include <ql/math/factorial.hpp>
#include <ql/math/distributions/normaldistribution.hpp>
#include <ql/math/solvers1d/brent.hpp>
#include <boost/function.hpp>
#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/bind.hpp>
#include <boost/math/distributions/students_t.hpp>
#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))
#pragma GCC diagnostic pop
#endif
namespace QuantLib {
CumulativeBehrensFisher::CumulativeBehrensFisher(
const std::vector<Integer>& degreesFreedom,
const std::vector<Real>& factors
)
: degreesFreedom_(degreesFreedom), factors_(factors),
polyConvolved_(std::vector<Real>(1, 1.)), // value to start convolution
a_(0.)
{
QL_REQUIRE(degreesFreedom.size() == factors.size(),
"Incompatible sizes in convolution.");
for(Size i=0; i<degreesFreedom.size(); i++) {
QL_REQUIRE(degreesFreedom[i]%2 != 0,
"Even degree of freedom not allowed");
QL_REQUIRE(degreesFreedom[i] >= 0,
"Negative degree of freedom not allowed");
}
for(Size i=0; i<degreesFreedom_.size(); i++)
polynCharFnc_.push_back(polynCharactT((degreesFreedom[i]-1)/2));
// adjust the polynomial coefficients by the factors in the linear
// combination:
for(Size i=0; i<degreesFreedom_.size(); i++) {
Real multiplier = 1.;
for(Size k=1; k<polynCharFnc_[i].size(); k++) {
multiplier *= std::abs(factors_[i]);
polynCharFnc_[i][k] *= multiplier;
}
}
//convolution, here it is a product of polynomials and exponentials
for(Size i=0; i<polynCharFnc_.size(); i++)
polyConvolved_ =
convolveVectorPolynomials(polyConvolved_, polynCharFnc_[i]);
// trim possible zeros that might have arised:
std::vector<Real>::reverse_iterator it = polyConvolved_.rbegin();
while(it != polyConvolved_.rend()) {
if(*it == 0.) {
polyConvolved_.pop_back();
it = polyConvolved_.rbegin();
}else{
break;
}
}
// cache 'a' value (the exponent)
for(Size i=0; i<degreesFreedom_.size(); i++)
a_ += std::sqrt(static_cast<Real>(degreesFreedom_[i]))
* std::abs(factors_[i]);
a2_ = a_ * a_;
}
Disposable<std::vector<Real> >
CumulativeBehrensFisher::polynCharactT(Natural n) const {
Natural nu = 2 * n +1;
std::vector<Real> low(1,1.), high(1,1.);
high.push_back(std::sqrt(static_cast<Real>(nu)));
if(n==0) return low;
if(n==1) return high;
for(Size k=1; k<n; k++) {
std::vector<Real> recursionFactor(1,0.); // 0 coef
recursionFactor.push_back(0.); // 1 coef
recursionFactor.push_back(nu/((2.*k+1.)*(2.*k-1.))); // 2 coef
std::vector<Real> lowUp =
convolveVectorPolynomials(recursionFactor, low);
//add them up:
for(Size i=0; i<high.size(); i++)
lowUp[i] += high[i];
low = high;
high = lowUp;
}
return high;
}
Disposable<std::vector<Real> >
CumulativeBehrensFisher::convolveVectorPolynomials(
const std::vector<Real>& v1,
const std::vector<Real>& v2) const {
#if defined(QL_EXTRA_SAFETY_CHECKS)
QL_REQUIRE(!v1.empty() && !v2.empty(),
"Incorrect vectors in polynomial.");
#endif
const std::vector<Real>& shorter = v1.size() < v2.size() ? v1 : v2;
const std::vector<Real>& longer = (v1 == shorter) ? v2 : v1;
Size newDegree = v1.size()+v2.size()-2;
std::vector<Real> resultB(newDegree+1, 0.);
for(Size polyOrdr=0; polyOrdr<resultB.size(); polyOrdr++) {
for(Size i=std::max<Integer>(0, polyOrdr-longer.size()+1);
i<=std::min(polyOrdr, shorter.size()-1); i++)
resultB[polyOrdr] += shorter[i]*longer[polyOrdr-i];
}
return resultB;
}
Probability CumulativeBehrensFisher::operator()(const Real x) const {
// 1st & 0th terms with the table integration
Real integral = polyConvolved_[0] * std::atan(x/a_);
Real squared = a2_ + x*x;
Real rootsqr = std::sqrt(squared);
Real atan2xa = std::atan2(-x,a_);
if(polyConvolved_.size()>1)
integral += polyConvolved_[1] * x/squared;
for(Size exponent = 2; exponent <polyConvolved_.size(); exponent++) {
integral -= polyConvolved_[exponent] *
Factorial::get(exponent-1) * std::sin((exponent)*atan2xa)
/std::pow(rootsqr, static_cast<Real>(exponent));
}
return .5 + integral / M_PI;
}
Probability
CumulativeBehrensFisher::density(const Real x) const {
Real squared = a2_ + x*x;
Real integral = polyConvolved_[0] * a_ / squared;
Real rootsqr = std::sqrt(squared);
Real atan2xa = std::atan2(-x,a_);
for(Size exponent=1; exponent <polyConvolved_.size(); exponent++) {
integral += polyConvolved_[exponent] *
Factorial::get(exponent) * std::cos((exponent+1)*atan2xa)
/std::pow(rootsqr, static_cast<Real>(exponent+1) );
}
return integral / M_PI;
}
InverseCumulativeBehrensFisher::InverseCumulativeBehrensFisher(
const std::vector<Integer>& degreesFreedom,
const std::vector<Real>& factors,
Real accuracy)
: normSqr_(std::inner_product(factors.begin(), factors.end(),
factors.begin(), 0.)),
accuracy_(accuracy), distrib_(degreesFreedom, factors) { }
Real InverseCumulativeBehrensFisher::operator()(const Probability q) const {
Probability effectiveq;
Real sign;
// since the distrib is symmetric solve only on the right side:
if(q==0.5) {
return 0.;
}else if(q < 0.5) {
sign = -1.;
effectiveq = 1.-q;
}else{
sign = 1.;
effectiveq = q;
}
Real xMin =
InverseCumulativeNormal::standard_value(effectiveq) * normSqr_;
// inversion will fail at the Brent's bounds-check if this is not enough
// (q is very close to 1.), in a bad combination fails around 1.-1.e-7
Real xMax = 1.e6;
return sign *
Brent().solve(boost::bind(std::bind2nd(std::minus<Real>(),
effectiveq), boost::bind<Real>(
&CumulativeBehrensFisher::operator (),
distrib_, _1)), accuracy_, (xMin+xMax)/2., xMin, xMax);
}
}
The error seems to be in the third line from the bottom. That's the one that's highlighted.
effectiveq), boost::bind<Real>(
&CumulativeBehrensFisher::operator (),
distrib_, _1)), accuracy_, (xMin+xMax)/2., xMin, xMax);
When I hover a mouse over it, it says
Error: more than one instance of overloaded function "boost::bind" matches the argument list: function template "boost_bi::bind_t " etc. Please see the attached screenshot
How can I fix this? Please help.
This came up quite a few times lately on the QuantLib mailing list. In short, the code worked with Boost 1.57 (the latest version at the time of the QuantLib 1.5 release) but broke with Boost 1.58.
There's a fix for this in the QuantLib master branch on GitHub, but it hasn't made it into a release yet. If you want to (or have to) use Boost 1.58, you can check out the latest code from there. If you want to use a released QuantLib version instead, the workaround is to downgrade to Boost 1.57.

C++ OOP Design Decisions [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I've written an aimbot for an open-source shooter called Assault Cube. Here is part of the source code:
Main.h:
/*
Control + 0 = enable aimbot
Control + 9 = enable vacuum hack
*/
#include "stdafx.h"
#ifndef MAIN_H
#define MAIN_H
#include "Player.h"
#include "Constants.h"
#include "Calculations.h"
#include <math.h>
Player players[32]; // need to give access to this to Calculations
int main() {
bool aimbotEnabled = false;
bool vacEnabled = false;
Player* closestTargetPointer = nullptr;
// [Base + DF73C] = Player 1 base
players[0] = Player(reinterpret_cast<char**>(Constants::baseAddress + 0xDF73C));
char** extraPlayersBase = *(reinterpret_cast<char***>(Constants::baseAddress + 0xE5F00));
// [Base + E5F00] = A
// [A + 0,4,8...] = Player 2/3/4... base
for (int i = 0; i < Calculations::getNumberOfPlayers() - 1; i++) {
players[i + 1] = Player(extraPlayersBase + i * 4);
}
while (true) {
if (GetAsyncKeyState(VK_CONTROL)) {
if (GetAsyncKeyState('0')) {
aimbotEnabled = !aimbotEnabled;
Sleep(500);
} else if (GetAsyncKeyState('9')) {
vacEnabled = !vacEnabled;
Sleep(500);
}
}
if (aimbotEnabled) {
closestTargetPointer = Calculations::getClosestTarget();
if (closestTargetPointer != nullptr) {
players[0].setCrosshairX(Calculations::getCrosshairHorizontalAngle(players[0], *closestTargetPointer));
players[0].setCrosshairY(Calculations::getCrosshairVerticalAngle(players[0], *closestTargetPointer));
}
}
if (vacEnabled) {
for (int i = 1; i < Calculations::getNumberOfPlayers(); i++) {
players[i].setX(players[0].getX() + 10);
players[i].setY(players[0].getY());
players[i].setZ(players[0].getZ());
}
}
Sleep(10);
}
}
#endif
Calculations.h:
#include "stdafx.h"
#ifndef CALCULATIONS_H
#define CALCULATIONS_H
#include "Player.h"
#include "Constants.h"
namespace Calculations {
/* Pythagorean's theorem applied twice for getting distance between two players in 3D space */
float getDistanceBetween(Player one, Player two) {
return sqrt(
(one.getX() - two.getX()) * (one.getX() - two.getX())
+ (one.getY() - two.getY()) * (one.getY() - two.getY())
+ (one.getZ() - two.getZ()) * (one.getZ() - two.getZ())
);
}
int getNumberOfPlayers() {
return *(reinterpret_cast<int*>(Constants::baseAddress + 0xE4E10));
}
Player* getClosestTarget() {
float smallestDistance;
int index = -1;
for (int i = 1; i < getNumberOfPlayers(); i++) {
if (players[i].getHP() > 0 && players[i].isVisible()) { // this is an error, because Calculations does not have access to the players array in Main
float tempDistance = getDistanceBetween(players[0], players[i]);
if (index == -1 || tempDistance < smallestDistance) {
smallestDistance = tempDistance;
index = i;
}
}
}
if (index == -1) {
return nullptr;
} else {
return &players[index];
}
}
float getCrosshairHorizontalAngle(Player me, Player target) {
float deltaX = target.getX() - me.getX();
float deltaY = me.getY() - target.getY();
if (target.getX() > me.getX() && target.getY() < me.getY()) {
return atanf(deltaX / deltaY) * 180.0f / Constants::pi;
} else if (target.getX() > me.getX() && target.getY() > me.getY()) {
return atanf(deltaX / deltaY) * 180.0f / Constants::pi + 180.0f;
} else if (target.getX() < me.getX() && target.getY() > me.getY()) {
return atanf(deltaX / deltaY) * 180.0f / Constants::pi - 180.0f;
} else {
return atanf(deltaX / deltaY) * 180.0f / Constants::pi + 360.0f;
}
}
float getCrosshairVerticalAngle(Player me, Player target) {
float deltaZ = target.getZ() - me.getZ();
float dist = getDistanceBetween(me, target);
return asinf(deltaZ / dist) * 180.0f / Constants::pi;
}
}
#endif
Errors:
1> Calculations.h
1>Calculations.h(26): error C2065: 'players' : undeclared identifier
1>Calculations.h(26): error C2228: left of '.getHP' must have class/struct/union
1>Calculations.h(26): error C2228: left of '.isVisible' must have class/struct/union
1>Calculations.h(27): error C2065: 'players' : undeclared identifier
1>Calculations.h(39): error C2065: 'players' : undeclared identifier
All these errors are because Calculations does not have access to the players array in Main. Is there any way I can give Calculations access to the players array?
Also, let me know if my decision of making Calculations a namespace was correct.
Add at the beginning of Calculations.h
extern Player players[32];
to tell the compiler to get the definition of players in another location / file.
The extern keyword is equivalent to declare without defining. It is a way to explicitly declare a variable, or to force a declaration without a definition...
The extern keyword declares a variable or function and specifies that
it has external linkage (its name is visible from files other than the
one in which it's defined). When modifying a variable, extern
specifies that the variable has static duration (it is allocated when
the program begins and deallocated when the program ends). The
variable or function may be defined in another source file, or later
in the same file. Declarations of variables and functions at file
scope are external by default.
Source here (+examples) and here.
Last Note : extern doesn't behave the same for functions and variables. more.
Put:
extern Player players[32];
Somewhere before line 26 of Calculations.h.
Having a global player array, as it would be with the extern keyword, is certainly not a good design decision.
A better design would probably define a world object that knows about anything that is currently in existence and could define what information is available to which actor. Players would then query this world object for information on their surrounding and make decisions based on that.
You might want to implement this world as a singleton, so that you can write static wrapper functions that silently supply the object to the calls, avoiding the hassle to look up the world object everywhere.

NLOpt with windows forms

I am suffering serious problems while trying to use nlopt library (http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial) in windows forms application. I have created following namespace which runs perfectly in console application.
#include "math.h"
#include "nlopt.h"
namespace test
{
typedef struct {
double a, b;
} my_constraint_data;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
my_constraint_data *d = (my_constraint_data *) data;
double a = d->a, b = d->b;
if (grad) {
grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
grad[1] = -1.0;
}
return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}
int comp()
{
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
my_constraint_data data[2] = { {2,0}, {-1,1} };
nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
nlopt_set_xtol_rel(opt, 1e-4);
double x[2] = { 1.234, 5.678 }; /* some initial guess */
double minf; /* the minimum objective value, upon return */
int a=nlopt_optimize(opt, x, &minf) ;
return 1;
}
}
It optimizes simple nonlinear constrained minimization problem. The problem arises when I try to use this namespace in windows form application. I am constantly getting unhandled exception in myfunc which sees "x" as empty pointer for some reason and therefore causes error when trying to access its location. I believe that the problem is somehow caused by the fact that windows forms uses CLR but I dont know if it is solvable or not. I am using visual studio 2008 and the test programs are simple console project (which works fine) and windows forms project (that causes aforementioned errors).
My test code is based on tutorial for C from the provided link. I although tried C++ version which once again works fine in console application but gives debug assertion failed error in windows forms application.
So I guess my questions is : I have working windows forms application and I would like to use NLOpt. Is there a way to make this work ?