The value of strings doesn't appear in eclipse mars CDT - eclipse

Why does the value of strings in Eclipse Mars CDT not appear in the expression or variables windows?
It appears {...} but i want to see the value itself under the value tab.
How can i do this?

What is going on here is CDT is showing the information that GDB is providing to it.
For a trivial program, with the debugger stopped on the line with return 0;
#include <string>
using namespace std;
int main() {
string mystring = "my string here";
return 0;
}
this is what I see in the CDT variable view:
which matches what I see in GDB:
(gdb) p mystring
$1 = {static npos = <optimised out>,
_M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>},
_M_p = 0x602028 "my string here"}}
Pretty Printing C++
However, what I suspect you want is the pretty printers for libstdc++ which makes the variables view look like this:
Create a ~/.gdbinit file with the following contents (updating the path for your machine)
python
import sys
sys.path.insert(0, '/usr/share/gcc-4.8/python/')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)
end
Then point your launch configuration at that gdbinit file and start debugging.
GDB wiki entry on the subject:
https://sourceware.org/gdb/wiki/STLSupport
GCC manual entry:
https://gcc.gnu.org/onlinedocs/libstdc++/manual/debug.html

Related

PostgreSQL C function: libpq doesn't link?

I want to write a C function for PostgreSQL. For this function I will need to query some data using libpq, so I started by writing a dummy function to test this part:
#define _XOPEN_SOURCE
#include <libpq-fe.h>
#include <postgres.h>
#include <fmgr.h>
#include <funcapi.h>
#include <executor/executor.h>
#include "test.h"
PG_FUNCTION_INFO_V1(getAnnotation);
Datum getAnnotation(PG_FUNCTION_ARGS) {
// Connection to the database
PGconn *conn = PQsetdbLogin("localhost",
"5432",
"",
"",
"postgres",
"postgres",
"password");
// Databases names
PGresult *res = PQexec (conn, "SELECT user FROM activity LIMIT 1;");
VarChar* i = PQgetvalue(res, 0, 0);
PG_RETURN_VARCHAR_P(i);
}
It is just supposed to return the first column of the first line of one of my tables. Pretty simple right ? Well it doesn't work.
When I try to use it within psql, it says :
ERROR: could not load library "/usr/local/lib/postgresql/test.so": Error relocating /usr/local/lib/postgresql/test.so: PQexec: symbol not found
The weird part is that both PQsetdbLogin and PQexec are in the libpq-fe.h file, but only the second one causes an error. If I comment the PQexec line, then PQsetdbLogin raises an error as well.
Here is the Makefile I use to build the code:
PG_CPPFLAGS = -I$(libpq_srcdir)
LDFLAGS_INTERNAL = -L$(libdir)
SHLIB_LINK_INTERNAL = $(libpq)
SHLIB_PREREQS = submake-libpq
EXTENSION = test
DATA = test--0.1.sql
MODULES = test
# REGRESS = ... # Script for tests
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
As you can see, I linked libpq therem so everything should work... But it doesn't and I don't know why.
I am using PostgreSQL 9.6 in a docker container.
If you want to link with external libraries, you need SHLIB_LINK, but that only works if you use MODULE_big instead of MODULES.
A working Makefile would be
PG_CPPFLAGS = -I$(libpq_srcdir)
SHLIB_LINK = $(libpq)
EXTENSION = test
DATA = test--0.1.sql
MODULE_big = test
OBJS = test.o
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
But there are other problems with your function:
VarChar is a varlena, but PQgetvalue returns a char *.
You'd have to convert the value to a varlena with code similar to this:
VarChar *result;
char *c = PQgetvalue(res, 0, 0);
result = (VarChar *) palloc(strlen(c) + VARHDRSZ);
strncpy(VARDATA(result), c, strlen(c));
SET_VARSIZE(result, strlen(c) + VARHDRSZ);
It is usually the wrong idea to write client code in a server function.
If all you need is to run a query inside the current session, use the Server Programming Interface.
I guess your function is only sample code, but you need to close the connection before the backend terminates, else you have a connection leak.

SWIG wrong encoded string crashes Python

I've a problem where all my SWIG wrappers that deals with strings crashes If I pass a wrong encoded string inside a std::string, I mean strings that contains èé and so on, characters valid for the current locale, but not UTF-8 valid.
On my code side, I have solved parsing the input as wide strings and convert them to UTF-8, but I would like to catch those kind of errors with an Exception rather than a crash, isn't supposed PyUnicode_Check to fail with those strings ?
Swig actually crashes in SWIG_AsCharPtrAndSize() when calling PyString_AsStringAndSize(), this is the swig generated code:
SWIGINTERN int
SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc)
{
#if PY_VERSION_HEX>=0x03000000
#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
if (PyBytes_Check(obj))
#else
if (PyUnicode_Check(obj))
#endif
#else
if (PyString_Check(obj))
#endif
{
char *cstr; Py_ssize_t len;
#if PY_VERSION_HEX>=0x03000000
#if !defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
if (!alloc && cptr) {
/* We can't allow converting without allocation, since the internal
representation of string in Python 3 is UCS-2/UCS-4 but we require
a UTF-8 representation.
TODO(bhy) More detailed explanation */
return SWIG_RuntimeError;
}
obj = PyUnicode_AsUTF8String(obj);
if(alloc) *alloc = SWIG_NEWOBJ;
#endif
PyBytes_AsStringAndSize(obj, &cstr, &len);
#else
PyString_AsStringAndSize(obj, &cstr, &len);
#endif
if (cptr) {
Crash happens to into the last PyString_AsStringAndSize visible.
I remark that strings are passed as std::string but in happens also with const char* without any kind of difference.
Thanks in advice !
Cannot reproduce. Edit your question and add a Minimal, Complete, Verifable Example if this example doesn't solve your issue and need further help:
test.i
%module test
%include <std_string.i>
%inline %{
#include <string>
std::string func(std::string s)
{
return '[' + s + ']';
}
%}
Demo:
Python 3.3.5 (v3.3.5:62cf4e77f785, Mar 9 2014, 10:35:05) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.func('ábc')
'[ábc]'
Problem was with 3.3.0 version we were still using, updating to 3.3.7 solved the problem, in the Python release notes there's several bug fixed in regards to PyUnicode_Check

Linking LAPACKE and Eclipse in Ubuntu

I am new to C++ and I am using Eclipse to write a script. My OS is Ubuntu. I need to use the LAPACKE package partially for my code. I however cannot manage to link Eclipse and LAPACKE. I am trying to compile the following sample code:
#include <stdio.h>
#include <lapacke.h>
int main (int argc, const char * argv[])
{
double a[5][3] = {1,1,1,2,3,4,3,5,2,4,2,5,5,4,3};
double b[5][2] = {-10,-3,12,14,14,12,16,16,18,16};
lapack_int info,m,n,lda,ldb,nrhs;
int i,j;
m = 5;
n = 3;
nrhs = 2;
lda = 3;
ldb = 2;
info = LAPACKE_dgels(LAPACK_ROW_MAJOR,'N',m,n,nrhs,*a,lda,*b,ldb);
for(i=0;i<n;i++)
{
for(j=0;j<nrhs;j++)
{
printf("%lf ",b[i][j]);
}
printf("\n");
}
return(info);
}
I am unable to compile the code as my Eclipse throws the error: "Udefined reference to LAPACKE_dgels". I have tried to link Eclipse to LAPACKE, for which I have added the path to LAPACKE header files in the "Paths and Symbols" tab of Eclipse. Can anyone help with what I need to do in order to resolve this issue? I should be missing something ...
I assume you are using gcc compiler. I guess you are missing -llapack flag in the compile arguments. If it doesn't work, try -llapacke. This flag (-l[LibraryName]) tells linker to use external binaries (see: gcc: Difference between -L and -l option AND how to provide complete path to a library).
Check out this question to see how to add compiler flags in Eclipse: How to add compiler options in Eclipse IDE

discrepancy between build result and Problems view in Eclipse CDT

I'm using Eclipse 4.2, with CDT, and MinGW toolchain on a Windows machine (although I've a feeling the problem has nothing to do with this specific configuration). The G++ compiler is 4.7
I'm playing with c++11 features, with the following code:
#include <iostream>
#include <iomanip>
#include <memory>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
int main( int argc, char* argv[] )
{
vector<int> v { 1, 2, 3, 4, 5, 6, 7 };
int x {5};
auto mark = remove_if( v.begin(), v.end(), [x](int n) { return n<x; } );
v.erase( mark, v.end() );
for( int x : v ) { cout << x << ", "; }
cout << endl;
}
Everything is very straight forward and idiomatic c++11. The code compiles with no problems on the command line (g++ -std=c++11 hello.cpp).
In order to make this code compile In eclipse, I set the compiler to support C++11:
Properties -> C/C++ Build -> Settings -> Miscellaneous -> Ohter Flags:
I'm adding -std=c++11
Properties -> C/C++Build -> Discovery Options -> Compiler invocation arguments:
Adding -std=c++11
That's the only change I did to either the global preferences or to the project properties.
First Question: Why do I've to change the flags in two places? When each compiler flags is used?
If I hit Ctrl-B, the project will build successfully, as expected, and running it from within eclipse show the expected result (It prints: '5, 6, 7,').
However, the editor view shows red marks of error on both the 'remove_if' line, and the 'v.erase' line. Similarly, the Problems view shows I've these two problems. Looking at the details of the problem, I get:
For the remove_if line: 'Invalid arguments. Candidates are: #0 remove_if(#0, #0, #1)
For the erase line: 'Invalid arguments Candidates are: '? erase(?), ? erase(?,?)'
Second questions: It appears there are two different builds: one for continues status, and one for the actual build. Is that right? If so, do they have different rule (compilation flags, include paths, etc.)?
Third question: In the problem details I also see: 'Name resolution problem found by the indexer'. I guess this is why the error message are so cryptic. Are those messages coming from MinGW g++ compiler or from Eclipse? What is this Name resolution? How do I fix?
Appreciate your help.
EDIT (in reply to #Eugene): Thank you Eugene. I've opened a bug on Eclipse. I think that C++11 is only partially to blame. I've cleaned my code from C++11 stuff, and removed the -std=c++11 flag from both compilation switch. And yet, the CodAn barks on the remove_if line:
int pred( int n ) { return n < 5; }
int main( int argc, char* argv[] )
{
vector<int> v;
for( int i=0; i<=7; ++i ) {
v.push_back( i );
}
vector<int>::iterator mark = remove_if( v.begin(), v.end(), pred );
v.erase( mark, v.end() );
for( vector<int>::iterator i = v.begin(); i != v.end(); ++i ) {
cout << *i << ", ";
}
cout << endl;
}
The code compiles just fine (with Ctrl-B), but CodAn doesn't like the remove_if line, saying: Invalid Arguments, Candidates are '#0 remove_if(#0,#0,#1)'.
This is a very cryptic message - it appears it misses to substitute arguments in format string (#0 for 'iterator' and #1 for 'predicate'). I'm going to update the bug.
Interestingly, using 'list' instead of 'vector' clears up the error.
However, as for my question, I'm curious about how the CodAn work. Does it uses g++ (with a customized set of flags), or another external tool (lint?), or does it do it internally in Java? If there is a tool, how can I get its command line argument, and its output?
Build/Settings - these flags will be included into your makefile to do actual build. Build/Discovery - these flags will be passed to a compiler when "scanner settings" are discovered by IDE. IDE will run compiler in a special mode to discover values of the predefined macros, include paths, etc.
I believe, the problems you are seeing are detected by "Codan". Codan is a static analysis built into the CDT editor, you may find its settings on "C/C++ General"/"Code Analysis". You should report the problem to the bugs.eclipse.org if you feel the errors shown are bogus. Note that CDT does not yet support all C++11 features.

How to hide console window of subprocess?

I'm trying to write a very simple program to replace an existing executable. It should munge its arguments slightly and exec the original program with the new arguments. It's supposed to be invoked automatically and silently by a third-party library.
It runs fine, but it pops up a console window to show the output of the invoked program. I need that console window to not be there. I do not care about the program's output.
My original attempt was set up as a console application, so I thought I could fix this by writing a new Windows GUI app that did the same thing. But it still pops up the console. I assume that the original command is marked as a console application, and so Windows automatically gives it a console window to run in. I also tried replacing my original call to _exec() with a call to system(), just in case. No help.
Does anyone know how I can make this console window go away?
Here's my code:
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
char* lpCmdLine,
int nCmdShow)
{
char *argString, *executable;
// argString and executable are retrieved here
std::vector< std::string > newArgs;
// newArgs gets set up with the intended arguments here
char const ** newArgsP = new char const*[newArgs.size() + 1];
for (unsigned int i = 0; i < newArgs.size(); ++i)
{
newArgsP[i] = newArgs[i].c_str();
}
newArgsP[newArgs.size()] = NULL;
int rv = _execv(executable, newArgsP);
if (rv)
{
return -1;
}
}
Use the CreateProcess function instead of execve. For the dwCreationFlags paramter pass the CREATE_NO_WINDOW flag. You will also need to pass the command line as a string as well.
e.g.
STARTUPINFO startInfo = {0};
PROCESS_INFORMATION procInfo;
TCHAR cmdline[] = _T("\"path\\to\\app.exe\" \"arg1\" \"arg2\"");
startInfo.cb = sizeof(startInfo);
if(CreateProcess(_T("path\\to\\app.exe"), cmdline, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startInfo, &procInfo))
{
CloseHandle(procInfo.hProcess);
CloseHandle(procInfo.hThread);
}
Aha, I think I found the answer on MSDN, at least if I'm prepared to use .NET. (I don't think I'm really supposed to, but I'll ignore that for now.)
System::String^ command = gcnew System::String(executable);
System::Diagnostics::Process^ myProcess = gcnew Process;
myProcess->StartInfor->FileName = command;
myProcess->StartInfo->UseShellExecute = false; //1
myProcess->StartInfo->CreateNowindow = true; //2
myProcess->Start();
It's those two lines marked //1 and //2 that are important. Both need to be present.
I really don't understand what's going on here, but it seems to work.
You need to create a non-console application (i.e. a Windows GUI app). If all this app does is some processing of files or whatever, you won't need to have a WinMain, register any windows or have a message loop - just write your code as for a console app. Of course, you won't be able to use printf et al. And when you come to execute it, use the exec() family of functions, not system().