I am working on a Qt5 project written in C++. Building the project gives an error:
C2440: '=': cannot convert from 'const char [9]' to 'char*'
Which points to the line of code below:
port_name= "\\\\.\\COM4";//COM4-macine, COM4-11 Office
SerialPort arduino(port_name);
if (arduino.isConnected())
qDebug()<< "ardunio connection established" << endl;
else
qDebug()<< "ERROR in ardunio connection, check port name";
//the following codes are omitted ....
What is the problem here, and how can I correct it?
In C++, in contrast to C, string literals are
const
. So any pointer to such a string literal must beconst
, too:String literals are constant data in C++ (compilers tend to store them in read-only memory when possible).
In C++11 and later, you can no longer assign a string literal directly to a pointer-to-non-const-char (
char*
) 1.1: though some C++11 compilers may allow it as a non-standard extension for backwards compatibility, which may need to be enabled manually via compiler flag.
So, you need to declare
port_name
as a pointer-to-const-char instead (const char *
orchar const *
). But then you will have to cast it back to a non-constchar*
when passing it toSerialPort()
:Or simply:
The alternative is to declare
port_name
as a non-constchar[]
buffer, copy the string literal into it, and then pass it toSerialPort()
: