J Hinton
J Hinton

Reputation: 157

serial port works in debug but not release c++ code blocks windows

I have an application which performs properly under the CodeBlocks debugger or on the release version if under the bin sub-directory of the project. If the release gets copied to anywhere else it cannot identify or open a serial port on the system. It seems like I must be missing something simple or its not linking to a .lib file.

I use a function to check for existing ports on the system from com1 to com20 when the program starts. Under the project directory it can be connected to a micro-controller device and communication works fine. I use this function to check each port number for existence.

//determine if a serial port does or does not exist
bool getComPortList(std::string portName)
{
    bool test;
    char* portNumber = new char[portName.length() + 1];
    for (unsigned int n = 0; n < portName.length(); n++)
    {
        portNumber[n] = portName[n];
    }
    HANDLE testSerial;
    testSerial = CreateFile(portNumber, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, NULL, NULL);
    if (testSerial == INVALID_HANDLE_VALUE)
    {
        test = false;
    }
    else
    {
        test = true;
    }
    CloseHandle(testSerial);
    delete[] portNumber;
    return test;
}

Upvotes: 0

Views: 1262

Answers (2)

user4581301
user4581301

Reputation: 33952

CreateFile is called with an unterminated string. I suggest using portName.c_str() instead of the roll-your-own string portNumber.

Why?

The loop generating portNumber copies the characters in the string, but leaves out the terminating NULL. Odds are pretty good that debug mode politely zeroes portNumber when newed so portNumber comes pre-terminated. Release mode will be compiling for speed and won't perform that which isn't explicitly requested, so no zeroing and no freebie NULL.

Why this works in one folder and not another could just be dumb unluck (Not lucky because an outright crash would be a lot easier to detect) or it could be something more sinister. Regardless, the unterminated string needs fixing.

Upvotes: 1

code_fodder
code_fodder

Reputation: 16371

It sounds like a deployment issue - i.e. running this in the build-environment seems ok, but when you move it "outside" of the environment it does not work "stand-alone".

You can use a free tool like: dependencywalker. Run this on your executable and it will tell you what dlls/libraries you need to copy along with the program to make it run stand-alone.

It might be a bit crude, but without seeing the whole of your project environment its hard to tell what the issue is.

In some build environments (like MS visual studio) you can tell it to include all the dependencies in the executable (makes it quite big).

Upvotes: 0

Related Questions