Here is a small program that incorporates a call to an Intel MKL library function and DLIB's optimization routine find_min_using_approximate_derivatives.
The code runs perfectly when compiled with the intel C++ compiler: icpc using the invocation:
icpc main.cpp -I /Users/Username/Code/dlib-18.16 -DDLIB_USE_BLAS -I$MKLROOT/include -L$MKLROOT/lib/ -lmkl_core -lmkl_intel_thread -lpthread -lm -lmkl_intel_lp64 -DENABLE_DLIB -DDLIB_USE_BLAS
or by disabling the DLIB related portion of the code via:
clang++ main.cpp -I$MKLROOT/include -L$MKLROOT/lib/ -lmkl_core -lmkl_intel_thread -lpthread -lm -lmkl_intel_lp64
C++ code
// #define ENABLE_DLIB
#ifdef ENABLE_DLIB
#include "dlib/optimization.h"
#endif
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include "mkl.h"
using namespace std;
#ifdef ENABLE_DLIB
using namespace dlib;
#endif
template<typename T>
void printArray(T *data, string name, int len){
cout << name << "\n";
for(int i=0;i<len;i++){
cout << data[i] << " ";
}
cout << "\n";
}
#ifdef ENABLE_DLIB
typedef matrix<double,0,1> column_vector;
double rosen (const column_vector& m)
{
const double x = m(0);
const double y = m(1);
return 100.0*pow(y - x*x,2) + pow(1 - x,2);
}
#endif
int main()
{
#ifdef ENABLE_DLIB
column_vector starting_point(2);
starting_point = 4, 8;
find_min_using_approximate_derivatives(bfgs_search_strategy(),
objective_delta_stop_strategy(1e-7),
rosen, starting_point, -1);
cout << "\nBFGS rosen minimum lies at:\n";
cout << "x = " << starting_point(0) << endl;
cout << "y = " << starting_point(1) << endl;
#endif
int len=10;
double *x=new double[len];
double *y=new double[len];
for(int i=0;i<len;i++){
x[i]=(double)std::rand()/RAND_MAX;
y[i]=(double)std::rand()/RAND_MAX;
}
printArray<double>(x, "x", len);
printArray<double>(y, "y", len);
//sum(x)
double x_sum=cblas_dasum(len,x,1);
cout<< "sum(x): "<< x_sum <<"\n";
}
Nevertheless, it fails replacing icpc with clang++ above with multiple errors of the following kind:
Error
In file included from /opt/intel/composer_xe_2015.3.187/mkl/include/mkl.h:48:
/opt/intel/composer_xe_2015.3.187/mkl/include/mkl_cblas.h:584:6: error: conflicting types for 'cblas_cgemm'
void cblas_cgemm(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE TransA,
^
/Users/Username/Code/dlib-18.16/dlib/matrix/matrix_blas_bindings.h:75:18: note: previous declaration is here
void cblas_cgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,
...suggesting a conflict between the cblas_* routines mirrored in MKL. The documentation for DLIB suggests using the DLIB_USE_BLAS preprocessor directive in order for it to link with MKL but evidently it doesn't seem to help using clang++.
How do I make this work?
Related
I am trying to build plugins in c++ using boost library. helper.h
Header file:
#include <string>
#ifndef HELPER_H
#define HELPER_H
class Helper
{
public:
std::string s;
void helper_new(std::string a);
};
#endif
I defined the member function in a file helper.cpp
#include "helper.h"
namespace boostfs = boost::filesystem;
namespace boostdll = boost::dll;
namespace dll = boost::dll;
// Member Functions()
void Helper::helper_new(std::string a)
{
//int i=0;
std::cout<<"Inside helper_new function!!";
std::cout<<"\n";
std::cout<<a;
std::cout<<"\n";
/*std::ofstream MyFile("/home/deepansh/Desktop/Plugin_example/outputs/helper.txt");
std::cout << "Writing in helper.txt\n"; */
/*for(i=0;i<LONG_MAX;i++)
for(int j=0;j<LONG_MAX;j++);*/
/*MyFile<<a+" ";
MyFile<<i;
MyFile<<"\n";
MyFile.close();*/
std::cout << "Done\n";
}
int main() {
Helper obj;
std::string a;
std::cout<<"Enter string u want to write?";
std::getline(std::cin, a);
obj.s=a;
int choice=1;
std::cout<<"which strat to use? \'1\' or \'2\' ?(default is 1)";
std::cin>>choice;
std::string file="strat"+std::to_string(choice);
boostfs::path lib_path = boostfs::current_path();
boost::filesystem::path p2(std::string(lib_path.string()).append("/plugins/").append(file).append(".so"));
boost::shared_ptr<plugin_api> plugin; // variable to hold a pointer to plugin variable
std::cout << "Loading the plugin" << std::endl;
plugin = dll::import<plugin_api>( // type of imported symbol is located between `<` and `>`
p2, // path to the library and library name
"plugin", // name of the symbol to import
dll::load_mode::append_decorations // makes `libmy_plugin_sum.so` or `my_plugin_sum.dll` from `my_plugin_sum`
);
plugin->handle_task(obj);
std::cout << plugin->print() << std::endl;
}
I called the member function from another file with the help of object of Helper class passed to it as argument(this is compiles as so file) strat1.cpp
#include "../helper.h"
#include <string>
namespace my_namespace {
class strat : public plugin_api {
public:
strat() {
std::cout << "Constructing start" << std::endl;
}
std::string print() const {
return "Hello from strat 1";
}
int handle_task(Helper a) {
//long i=0;
//std::ofstream fout;
//fout.open("/home/deepansh/Desktop/Plugin_example/outputs/strat1.txt");
std::cout<<"Inside strat 1";
std::cout<<"\n";
/*for(i=0;i<LONG_MAX;i++)
for(int j=0;j<LONG_MAX;j++);*/
//fout<<a.s+" ";
//fout<<i;
//fout<<"\n";
//fout.close();
std::cout<<a.s;
std::cout<<"\n";
std::cout<<"going to the helper class function.";
std::string p="Hello man. What's up?";
a.helper_new(p); //error is here
return 0;
}
~strat() {
std::cout << "Destructing strat ;o)" << std::endl;
}
};
I am getting this error ./a.out: symbol lookup error: /home/deepansh/Desktop/Plugin_example/plugins/strat1.so: undefined symbol: _ZN6Helper10helper_newENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
When compiling the code can someone help. compiling:
Convert the plugin library(plugin implementation) to object file by using:
gcc -c -Wall -Werror -fpic strat1.c ../helper.cpp //here -wall and -Werror are for warnings
Then convert the .o files to .so files using(creating shared library from object file) :
gcc -shared -o strat1.so strat1.o
g++-8 helper.cpp -L/usr/lib/x86_64-linux-gnu -lboost_filesystem -L/usr/lib/x86_64-linux-gnu -lboost_system -ldl
when I run the executable a.out the error occurs
I want to do a fft in my c++ project, and show it afterwards as an image. In order to do the fft, I am using fftw++, and for displaying the image I wanted to use the CImg-library. Thus I started with the demo project from here. When compiling it, everything works. As soon as I add the CImg-header, it fails with the error
test.cpp: In function ‘int main()’:
test.cpp:18:12: error: ‘f’ was not declared in this scope
Complex *f=ComplexAlign(n);
My file looks like
#include "fftw++.h"
#include "CImg.h"
// Compile with:
// g++ -I .. -fopenmp example0.cc ../fftw++.cc -lfftw3 -lfftw3_omp
//using namespace std;
//using namespace utils;
//using namespace fftwpp;
//using namespace cimg_library;
int main()
{
fftwpp::fftw::maxthreads=get_max_threads();
std::cout << "1D complex to complex in-place FFT, not using the Array class"
<< std::endl;
unsigned int n=4;
Complex *f=utils::ComplexAlign(n);
fftwpp::fft1d Forward(n,-1);
fftwpp::fft1d Backward(n,1);
for(unsigned int i=0; i < n; i++) f[i]=i;
std::cout << "\ninput:" << std::endl;
for(unsigned int i=0; i < n; i++) std::cout << f[i] << std::endl;
Forward.fft(f);
std::cout << "\noutput:" << std::endl;
for(unsigned int i=0; i < n; i++) std::cout << f[i] << std::endl;
Backward.fftNormalized(f);
std::cout << "\ntransformed back:" << std::endl;
for(unsigned int i=0; i < n; i++) std::cout << f[i] << std::endl;
utils::deleteAlign(f);
}
and is compiled with
g++ -I .. -fopenmp test.cpp ../fftw++.cc -lfftw3 -lfftw3_omp
My g++ version is 4.8.5. Adding the Complex.h-header does not help either. What can I do in order to combine both libraries?
Edit: Further research shows that using the C-library complex.h and CImg.h results in a lot of compilation problems, combining the library Complex.h from the fftw++-package results also in errors, only the complex-include from C++ can be used together with the CImg.h-include file. Reason: Unknown till now.
My solution (even if it is not perfect) is, that I created a second cpp-file:
second.cpp:
#include "CImg.h"
//Code for images
void example(void){
}
and an include-file for that:
second.h:
#ifndef SECOND_H
#define SECOND_H
void example(void);
#endif /* SECOND_H */
If I only include that include file instead of CImg.h, I can use both fftw++ and CImg.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
/*Header.h file*/
#include <iostream>
using namespace std;
int main(){
/*Menu*/
/*case1:
int x;
cout << "Input ammount:";
cin >> x
sugarcake(x)*/
/*case2:
something else
*/
}
/*sugarcake.cpp file*/
#include <iostream>
#include "Header.h"
using namespace std;
void sugarcake(int x) {
cout << (x * 0.75) << "st egg" << endl;
cout << (x * 0.75) << "dl sugar" << endl;
cout << (x * 0.5) << "tsk vanillasugar" << endl;
cout << (x * 0.5) << "tsk blabla" << endl;
cout << (x * 0.75) << "dl wheatflour" << endl;
cout << (x * 18.75) << "gram butter" << endl;
cout << (x * 0.25) << "dl water" << endl;
}
How do i make this work or have i understood it completely wrong? (Started out with C++ yesterday so please be kind and i haven't been able to find any clear answer that works for me elsewhere)
TL DR: Call the function sugarcake(int x) in sugarcake.cpp inside the Header.h
You should not put code in the header file, instead use two source (.cpp) files, and let the header file only contain a declaration of (in your case) the sugarcake function.
So the header file should look something like
// These first two line (and the last line of the file) is part of
// a header include guard (see https://en.wikipedia.org/wiki/Include_guard)
#ifndef HEADER_H
#define HEADER_H
void sugarcake(int x);
#endif // HEADER_H
The sugarcake.cpp file:
#include <iostream>
#include "header.h" // Technically we don't need to include the header
// file here, but it's always a good idea to do
// anyway
void sugarcake(int x) {
...
}
And finally the main.cpp file:
#include <iostream>
#include "header.h"
int main() {
int x;
std::cin >> x;
sugarcake(x);
}
How to build this depends on your environment, but if you're using GCC from the command line then you do like this
$ g++ -Wall -Wextra main.cpp sugarcake.cpp -o sugarcake
The -Wall and -Wextra options are to enable extra warnings, always a good idea. The -o options tells g++ what to name the executable program it creates. The two source files are the files you just created.
We use header files to describe functions which will be used after in another occasion per say.
So I will show how I organize my functions in the header files:
/* header.h
* include guards below, it is very import to use it to be sure you'r not
* including things twice.
*/
#ifndef HEADER_H
#define HEADER_H
// I write function prototypes in the header files.
int sum(int &a, int &b);
#endif // HEADER_H
The definition of the function is written in the header.cpp
// header.cpp
#include "header.h"
int sum(int &a, int &b)
{
int total = a + b;
return total;
}
To use that function in main.cpp you just have to include the header.cpp
// main.cpp
#include <iostream>
#include "header.h"
int main(int argc, char *argv[])
{
int a = 5;
int b = 4;
int total = sum(a, b);
std::cout << "The total sum of the 4 and 5 numbers is: " << total << std::endl;
}
See how it is made? Then you can compile the cpp files and it will work!
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can templates only be implemented in the header file?
Here's my make file:
#!/usr/bin/make -f
compiler = g++
compiler_flags = -Wall -I /usr/include/c++/4.5
debug_flags = -D DEBUG -g
binary_filename = sort_testing.bin
all: clean release
release:
$(compiler) $(compiler_flags) main.cpp sort.o -o $(binary_filename)
debug: sort.o
$(compiler) $(debug_flags) $(compiler_flags) main.cpp sort.o -o $(binary_filename)
run:
./$(binary_filename)
clean:
rm -f *.o $(binary_filename)
sort.o:
$(compiler) $(debug_flags) $(compiler_flags) -c sort.cpp
Here are my C++ Files:
// sort.hpp
#ifndef SORT_H
#define SORT_H
namespace sort{
template<class T> void swap(T*,int,int);
}
#endif
// sort.cpp
#include "sort.hpp"
namespace sort{
template<class T>
void swap(T* items, int index_a, int index_b){
T t = items[index_a];
items[index_a] = items[index_b];
items[index_b] = t;
}
}
// main.cpp
#include <iostream>
#include <exception>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#include "sort.hpp"
using namespace sort;
#define NUM_INTS 5
int main(int argc, char** argv){
try{
cout << "\n\n\n";
srand(time(NULL));
int * int_coll = new int[NUM_INTS];
for (int x = 0; x < NUM_INTS; x++)
int_coll[x] = rand() % 100 + 1;
cout << "Before swap" << endl;
for (int x = 0; x < NUM_INTS; x++)
cout << "int " << x << " == " << int_coll[x] << endl;
cout << "\n\n\n";
cout << "Swapping ints" << endl;
swap<int>(int_coll, 0, 1);
cout << "AFter swap" << endl;
for (int x = 0; x < NUM_INTS; x++)
cout << "int " << x << " == " << int_coll[x] << endl;
}catch(exception& e){
cout << "Exception: " << e.what() << endl;
}
return 0;
}
And, here's my problem:
./make clean debug
rm -f *.o sort_testing.bin
g++ -D DEBUG -g -Wall -I /usr/include/c++/4.5 -c sort.cpp
g++ -D DEBUG -g -Wall -I /usr/include/c++/4.5 main.cpp sort.o -o sort_testing.bin
/tmp/ccRl2ZvH.o: In function `main':
/home/dev/c++/sorting/main.cpp:33: undefined reference to `void sort::swap<int>;(int*, int, int)'
collect2: ld returned 1 exit status
make: *** [debug] Error 1
Any idea how to resolve this issue?
Template definitions need to either be visible at the point of use (so that they can be implicitly instantiated) OR you need to explicitly instantiate them (in this case the linker will bring the explicit instantiation and the usage together).
In your situation I would go with option one (and implicit instantiation). This means you need to move the template definition (of the template) into the header file:
// sort.hpp
#ifndef SORT_H
#define SORT_H
namespace sort{
template<class T>
void swap(T*,int,int)
{
T t = items[index_a];
items[index_a] = items[index_b];
items[index_b] = t;
}
}
#endif
Alternatively (but less useful in the general case (but has its uses)) is explicit template instantiation. Here you define in sort.cpp which variants of the template you want to have defined.
// sort.cpp
#include "sort.hpp"
namespace sort{
template<class T>
void swap(T* items, int index_a, int index_b){
T t = items[index_a];
items[index_a] = items[index_b];
items[index_b] = t;
}
// Define an explicit function template instantiation.
// Here we define that the integer version of the template must exist.
template void swap<int>(int*,int,int);
}
This is useful when you want to limit the number of versions of a template are available.
Template definitions must be in the same file. So define the function in the header file itself.
Or include the .cpp file in the header at the bottom as:
// sort.hpp
#ifndef SORT_H
#define SORT_H
namespace sort{
template<class T> void swap(T*,int,int);
}
#include "sort.cpp" //<--------------- this!
#endif
You can not define templates in a .cpp file. The definition of swap should be in the sort.hpp file only. See this FAQ Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file? for more details.
Greeting Everyone
I'm trying to compile and run a multi-language code in C, C++ and fortran using gcc, g++ & f77 respectively in UNIX. My program consists of two parts, one in C, the other in C++. They interface via a main() writen in C+, while the fortran code can be ignored for this case.
I have been having numerous issues with this, most noticabbly a Segmentation Error thats been occuring as I run the executable. The previous two topics of mine have whittled it down, unfortunatly nothing seems to be solving the problem outright other than completely removing any input/output processes in either half of my program, which just isn't feasible.
Accessing public class memory from C++ using C
Output conflicts between C & C++
I need to locate the reason why I recieve Segmentation Errors when I use input/outputs in both parts of my program. All sources compile, all link successfully and I know that each part (C & C++) works when linked alone with no such Segmentation Errors (with modifications to let them work alone of course). I've included all the code that interfaces between the two parts and performs input/output functions.
Any help would be much appriciated.
Makefile
products: SlowDynamic.exe
SlowDynamic.exe: main.o SA.o mersenne.o CFE.o BCs.o EMatrix.o Numbering.o KMatrix.o Solve.o MA_57.o blas.o MA_57_Depend.o Metis.o
f77 -L/usr/sfw/lib -R/usr/sfw/lib -lgcc_s -lstdc++ -o SlowDynamic.exe main.o \
SA.o mersenne.o CFE.o MA_57.o blas.o MA_57_Depend.o Metis.o\
BCs.o EMatrix.o Numbering.o KMatrix.o Solve.o
main.o: main.cpp
g++ -c -o main.o main.cpp
SA.o: SA.cpp
g++ -c -o SA.o SA.cpp
mersenne.o: mersenne.cpp
g++ -c -o mersenne.o mersenne.cpp
CFE.o: CFE.c
gcc -c -o CFE.o CFE.c
MA_57.o: MA_57.f
f77 -c -o MA_57.o MA_57.f
blas.o: blas.f
f77 -c -o blas.o blas.f
MA_57_Depend.o: MA_57_Depend.f
f77 -c -o MA_57_Depend.o MA_57_Depend.f
Metis.o: Metis.f
f77 -c -o Metis.o Metis.f
BCs.o: BCs.c
gcc -c -o BCs.o BCs.c
EMatrix.o: EMatrix.c
gcc -c -o EMatrix.o EMatrix.c
Numbering.o: Numbering.c
gcc -c -o Numbering.o Numbering.c
KMatrix.o: KMatrix.c
gcc -c -o KMatrix.o KMatrix.c
Solve.o : Solve.c
gcc -c -o Solve.o Solve.c
clean:
rm *.o Main.exe *.gpi
main.ccp
#include <iostream>
#include "SA.h"
using namespace std;
int main()
{
Initial.Initialize();
Parent.SA(Initial.Write);
system ("PAUSE");
return 0;
}
SA.h
#ifndef SA_H
#define SA_H
#include <vector>
class SimAnneal {
std::vector< std::vector<float> > DensityDomain;
float Solid_Ele_Num, Void_Ele_Num;
float Solid, Void;
double Energy;
double Time;
void Metropolis (double, int, int);
void Next_State (double, int);
double Schedule (double, int);
double ObjFunction ();
void Distribute ();
void Mutate ();
void Convert ();
void PrintDomain ();
void WriteResults (double, double, double, double, double);
public:
int x_max, y_max;
...
std::vector<float> DensityArray;
std::vector<float> EnergyArray;
...
void SA (int);
void Initialize ();
};
extern SimAnneal Initial, Parent, Child, Mutation, Best;
#endif
SA.cpp
include <math.h>
#include <iostream>
#include <fstream>
#include <time.h>
#include <vector>
#include "SA.h"
#include "CFE.h"
#include "randomc.h"
using namespace std;
SimAnneal Initial, Parent, Child, Mutation, Best;
...
void SimAnneal::Initialize ()
{
x_max = ReturnX();
y_max = ReturnY();
EnergyArray.resize(x_max*y_max);
DensityArray.resize(x_max*y_max);
...
Energy = ObjFunction();
}
...
void SimAnneal::PrintDomain ()
{
static ofstream OutputFile;
if (!OutputFile.is_open())
{
char FileName [] = "DensityDomain.txt";
OutputFile.open(FileName);
if (!OutputFile)
{
cerr << "Failed to open " << FileName << endl;
exit(EXIT_FAILURE);
}
//cout << "\nGenerating 'DensityDomain.txt'... \n" << endl;
}
for (int y = 0; y < y_max; y++)
{
for (int x = 0; x < x_max; x++)
{
OutputFile << DensityDomain[y][x] << " ";
}
OutputFile << endl;
}
OutputFile.close();
}
void SimAnneal::WriteResults (double i, double T, double x, double y, double z)
{
static ofstream OutputFile;
if (!OutputFile.is_open()) //check is file has been opened
{
char FileName [] = "Results.txt";
OutputFile.open(FileName);
if (!OutputFile)
{
cerr << "Failed to open " << FileName << endl;
exit(EXIT_FAILURE); //abort program
}
//cout << "\nWriting to file in progress... \n" << endl;
OutputFile << "Iterations" << '\t' << "Temperatures" << '\t' << "Sum Strain Energy" << endl; //<< "SwapNum1" << '\t' << "SwapNum2" << '\t' << "Distance" << endl;
OutputFile << endl;
Initial.Time = (int)time(0);
}
OutputFile << i << '\t' << T << '\t' << z << endl; //'\t' << y << '\t' << z << endl;
if (i == N_max || T <= T_abs)
{
Parent.Time = (int)time(0);
OutputFile << endl
<< "Settings: " << endl
<< "Initial Temperature: " << Initial.Temp << endl
<< "Temperature Iterations: " << i << endl
<< "Step Iterations: " << N_step << endl
<< endl
<< "Results: " << endl
<< "Final Temperature: " << Temp << endl
<< "Minimum: " << Energy << endl
<< "Computational Time (s): " << (Parent.Time-Initial.Time) << endl;
OutputFile.close();
}
}
CFE.h
#ifdef __cplusplus
extern "C" {
#endif
int ReturnX ();
int ReturnY ();
void CFE(float density[], float energy[], int Length);
#ifdef __cplusplus
}
#endif
CFE.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "BCs.h"
#include "EMatrix.h"
#include "Numbering.h"
#include "KMatrix.h"
#include "fg_types.h"
#include "Solve.h"
int ReturnX ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
fclose(infile);
return elemX;
}
int ReturnY () { Same but returns elemY }
void CFE(float density[], float energy[])
{
// Extensive use of fscanf(), printf() & fprintf()
// and the following:
FILE *outfile;
outfile = fopen("File.txt", "w");
if(outfile == NULL){
}
else{
for(n=0;n<8;n++)
{
for(m=0;m<8;m++)
{
fprintf(outfile,"%f",KE[n][m]);
fprintf(outfile,"\t");
}
fprintf(outfile,"\n");
}
}
fclose(outfile);
}
I'd suggest going through your code with a critical eye, and checking out everything that looks even remotely odd.
I'd do it for you but C++ isn't in my rotation at the moment and I'm tripping on false positives. For example, this caught my eye:
if (!OutputFile.is_open())
{
char FileName [] = "DensityDomain.txt";
OutputFile.open(FileName);
if (!OutputFile)
{
cerr << "Failed to open " << FileName << endl;
exit(EXIT_FAILURE);
}
//cout << "\nGenerating 'DensityDomain.txt'... \n" << endl;
}
Half way down you're testing if OutputFile is null, after already calling is_open() and open() on it. It looked to me as if either 1) OutputFile won't be null or 2) you shouldn't be calling methods on it before you test it. But I was wrong.
See what I mean?