How to call a script from inside CPP code in linux - c++

I am new to C++ coding using linux.Hence, my apologies if my question is trivial.
I need some help regarding calling some script/executable from inside a cpp file.
I downloaded few libraries (Blas, Lapack, libtsnnls-2.3.3). Configured and made executable. This executable was created when I configured and compiled libtsnnls-2.3.3.
I can call from command line:
cd /home/dkumar/libtsnnls-2.3.3/tsnnls
./genb_test
Now, I want to call the same command from a cpp file. It's something similar to "HelloWorld.cpp"
My Attempt (modified based on suggestion of #Biffer #timrau:
// 'Hello World!' program
#include <stdio.h> /* defines FILENAME_MAX */
#include <cstdlib> /* MODIFIED std::system */
#include <iostream>
#ifdef _MSC_VER
#include "direct.h"
#define GetCurrentDir _getcwd // window ??
#else
#include "unistd.h"
#define GetCurrentDir getcwd
#endif
int main()
{
std::cout << "Hello World!" << std::endl;
// const char *ParentFolder = "/home/dkumar/All_Matlab_Codes_DKU";
const char *ParentFolder = "/home/dkumar/libtsnnls-2.3.3/tsnnls/";
int res3 = chdir(ParentFolder);
// exceuting the command('./genb_test')
std::system('./genb_test');
return 0;
}
I get the following errors:
HelloWorld.cpp:36:10: warning: character constant too long for its type [enabled by default]
system('./genb_test');
^
HelloWorld.cpp: In function ‘int main()’:
HelloWorld.cpp:36:23: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]
system('./genb_test');
^
In file included from /usr/include/c++/4.8/cstdlib:72:0,
from HelloWorld.cpp:4:
/usr/include/stdlib.h:717:12: error: initializing argument 1 of ‘int system(const char*)’ [-fpermissive]
extern int system (const char *__command) __wur;

In c++ ' is used for characters ('a') and " is used for strings ("aaaa").
If you edit system('./genb_test') to be system("./genb_test") it might work.

You have single ' when calling your script. You want double "
#include <cstdlib> /* MODIFIED std::system */
int main()
{
// executing the command("./genb_test")
std::system("./genb_test");
return 0;
}

there is a function named system which could start a shell process to run your script, to do this, you need first include cstdlib header and then call the system function in your code
example
#include <cstdlib>
int main()
{
system("./myscript.sh");
}
The function system need a parameter of type std::string or a C-style string, so you will need the double quotation mark

Related

How can I deal with the following : "error: the value of 'foo' is not usable in a constant expression."?

I am using Yaml-cpp and Eigen in my small project.
For example, in cfg_.yaml
foo:
bar: 15
In constants.h
#pragma once
#include "yaml-cpp/yaml.h"
#include <iostream>
#ifndef DO_FORWARD_GRADIENT_constexprANTS_H
#define DO_FORWARD_GRADIENT_constexprANTS_H
const std::string yaml_path = "${MYWORKSPACE}/cfg_.yaml";
YAML::Node cfg_ = YAML::LoadFile(yaml_path);
const int nq = cfg_["foo"]["bar"].as<int>();
#endif
In main.cpp
#include <Eigen.h>
#include <constants.h>
int main(){
Eigen::Matrix<double,nq,1> matrix_test;
matrix_test.setZero();
return 0;
}
But, the following error occurs:
error: the value of 'nq' is not usable in a constant expression.
I figured out that this happens because the variable is not defined at compile time.
I want to use the yaml file to reduce the build time when changing the variables.
For example, I want to call the value of variable in constants.h from the cfg.yaml.
How can I solve the error?

How do I print Unicode characters using ncurses in C++?

I am making a chess game on the C++ console and I can't seem to be able to output the Unicode symbols for the chess pieces.
#define whiteking 0x2654
int main()
{
setlocale(LC_ALL, "");
initscr();
keypad(stdscr, TRUE);
wchar_t c = whiteking;
add_wch(c);
getch();
endwin();
return 0;
}
The error returned is:
In file included from main.cpp:4:0:
main.cpp: In function ‘int main()’:
main.cpp:624:5: error: invalid conversion from ‘wchar_t’ to ‘const cchar_t*’
[-fpermissive]
add_wch(c);
^
/usr/include/ncursesw/curses.h:1703:28: note: initializing argument 2 of
‘int wadd_wch(WINDOW*, const cchar_t*)’
extern NCURSES_EXPORT(int) wadd_wch (WINDOW *,const cchar_t *); /*
implemented */
The includes are:
#include <locale.h>
#include <ncursesw/ncurses.h>
#include <wchar.h>
#include <stdio.h>
None of the other stack overflow answers seems to help me. I am using this online compiler. Thank you for your help!
X/Open Curses (ncurses) uses a variety of datatypes. cchar_t is a structure, while wchar_t is not.
You can do what was intended using a different function:
#include <curses.h>
#include <locale.h>
#define whiteking 0x2654
int main()
{
setlocale(LC_ALL, "");
initscr();
keypad(stdscr, TRUE);
wchar_t s[2];
s[0] = whiteking;
s[1] = 0;
addwstr(s);
getch();
endwin();
return 0;
}

Accessing elements in namespace defined in header file

I am trying to access variables and functions defined in a namespace in a header file. However, I get the error: xor.cpp:(.text+0x35): undefined reference to "the function in header file" collect2: error: ld returned 1 exit status. It seems to me that the compilation steps are OK after reading this post, and also because I can access variables in this header file, but calling the function returns the error mentioned above. My question is: How can I access those functions in the namespace from my main.cpp ? What am I doing wrong ?
The case with a class is clear to me, but here I don't understand because I am not supposed to create an object, so just calling the namespace in front should be OK (?).
Edit
After changes suggested by Maestro, I have updated the code the following way, but it still doesn't work. The error I get is the same. If I define using NEAT::trait_param_mut_prob = 6.7; I get the error: xor.cpp:127:36: error: expected primary-expression before ‘=’ token
Main c++
#include "experiments.h"
#include "neat.h"
#include <cstring>
int main(){
const char *the_string = "test.ne";
bool bool_disp = true;
NEAT::trait_param_mut_prob;
trait_param_mut_prob = 6.7;
NEAT::load_neat_params(the_string ,bool_disp);
std::cout << NEAT::trait_param_mut_prob << std::endl;
return 0;
}
neat.h
#ifndef _NERO_NEAT_H_
#define _NERO_NEAT_H_
#include <cstdlib>
#include <cstring>
namespace NEAT {
extern double trait_param_mut_prob;
bool load_neat_params(const char *filename, bool output = false); //defined HERE
}
#endif
neat.cpp
#include "neat.h"
#include <fstream>
#include <cmath>
#include <cstring>
double NEAT::trait_param_mut_prob = 0;
bool NEAT::load_neat_params(const char *filename, bool output) {
//prints some stuff
return false;
};
Makefile
neat.o: neat.cpp neat.h
g++ -c neat.cpp
You are breaking the "ODR rule" (One-Definition-Rule): you've defined trait_param_mut_prob and load_neat_params twice once in source file neat.cpp and second in main.cpp so simply remove those lines from main.cpp:
//double NEAT::trait_param_mut_prob; //NEAT is the namespace
//bool NEAT::load_neat_params(const char* filename, bool output); //function defined in the namespace
Add #endif in you header neat.h.
to make your function and variable available in main just use using or fully-qualify the call because as I've seen you intend to re-declare them in main to avoid fully qualifying them: in main:
int main()
{
using NEAT::trait_param_mut_prob;
using NEAT::load_neat_params;
const char* the_string = "test.ne";
bool bool_disp = true;
trait_param_mut_prob = 6.7;//works perfectly
load_neat_params(the_string, bool_disp);
// or fully-qualify:
//NEAT::load_neat_params(the_string, bool_disp);
//NEAT::trait_param_mut_prob = 6.7;//works perfectly
}
Also it is erroneous that your function load_neat_params doesn't return a bool value. So make it either return true or false.

error: uint64_t was not declared in this scope when compiling C++ program

I am trying out a simple program to print the timestamp value of steady_clock as shown below:
#include <iostream>
#include <chrono>
using namespace std;
int main ()
{
cout << "Hello World! ";
uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
cout<<"Value: " << now << endl;
return 0;
}
But whenever I am compiling like this g++ -o abc abc.cpp, I am always getting an error:
In file included from /usr/include/c++/4.6/chrono:35:0,
from abc.cpp:2:
/usr/include/c++/4.6/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.
abc.cpp: In function âint main()â:
abc.cpp:7:3: error: âuint64_tâ was not declared in this scope
abc.cpp:7:12: error: expected â;â before ânowâ
abc.cpp:8:22: error: ânowâ was not declared in this scope
Is there anything wrong I am doing?
Obviously, I'm not following certain best practices, but just trying to get things working for you
#include <iostream>
#include <chrono>
#include <cstdint> // include this header for uint64_t
using namespace std;
int main ()
{
{
using namespace std::chrono; // make symbols under std::chrono visible inside this code block
cout << "Hello World! ";
uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
cout<<"Value: " << now << endl;
}
return 0;
}
and then compile using C++11 enabled (c++0x in your case)
g++ -std=c++0x -o abc abc.cpp
You should include stdint.h file.
If you really want to include, add "#define __STDC_LIMIT_MACROS"
Ref: https://stackoverflow.com/a/3233069/6728794

C++ stat.h incomplete type and cannot be defined

I am having a very strange issue with stat.h
At the top of my code, I have declarations:
#include <sys\types.h>
#include <sys\stat.h>
And function prototype:
int FileSize(string szFileName);
Finally, the function itself is defined as follows:
int FileSize(string szFileName)
{
struct stat fileStat;
int err = stat( szFileName.c_str(), &fileStat );
if (0 != err) return 0;
return fileStat.st_size;
}
When I attempt to compile this code, I get the error:
divide.cpp: In function 'int FileSize(std::string)':
divide.cpp:216: error: aggregate 'stat fileStat' has incomplete type and cannot be defined
divide.cpp:217: error: invalid use of incomplete type 'struct stat'
divide.cpp:216: error: forward declaration of 'struct stat'
From this thread: How can I get a file's size in C?
I think this code should work and I cannot figure out why it does not compile. Can anybody spot what I am doing wrong?
Are your \'s supposed to be /'s or am I just confused about your environment?
UNIX MAN page:
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int stat(const char *restrict path, struct stat *restrict buf);
If you're on Windows (which I'm guessing you might be because of the \'s), then I can't help because I didn't even know that had stat.