Question

I am working on a UDP socket program in windows visual studio. I am getting an error for sprintf statement. How to correct it? My code is:

    for (i = 0; i < 30;i++) //take-off
{
    printf("send AT*REF:take off\n");
            sprintf(command, "AT*REF=%d,290718208\r", seq++);



    rc = sendto(sd, command, strlen(command) + 1, flags, (struct sockaddr *) &droneAddr, sizeof(droneAddr));
    if (rc<0) {
        printf("%s: can not send data\n", argv[0]);
            return(1);
                    }
     }

The errors I am getting are :

Error   1 error C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
Error   1 error LNK2019: unresolved external symbol __imp__bind@12
Error   2 error LNK2019: unresolved external symbol __imp__htonl@4 referenced in function _main 
Error   3 error LNK2019: unresolved external symbol __imp__htons@4
Error   4 error LNK2019: unresolved external symbol __imp__sendto@24
Error   5 error LNK2019: unresolved external symbol __imp__socket@12
Error   6 error LNK2019: unresolved external symbol __imp__gethostbyname@4
Error   7 error LNK1120: 6 unresolved externals 
Was it helpful?

Solution

printf and its sister function sprintf are considered unsafe due to the amount of undefined behaviour they emit if used incorrectly.

Visual Studio is disabling these functions by default.

But, since they are part of the C++ standard library, you can use them. But Visual Studio will only allow you to do that if you include the line

#define _CRT_SECURE_NO_WARNINGS

before the relevant standard library headers are included.

Alternatively, include _CRT_SECURE_NO_WARNINGS in your project preprocessor settings (which is what I do).

(By the way, Visual Studio is emitting a very helpful error message in this instance. Do try to learn to interpret them.)

OTHER TIPS

For most of the errors in your question you need to add ws2_32.lib to the library that the project links to (in the VS project's Linker | Input | Additional Dependencies property).

Other answers/comments have addressed the sprintf() problem: either defined the macro _CRT_SECURE_NO_WARNINGS or use a version of sprintf() that is deemed safe by Microsoft, such as sprintf_s(). I wish MSVC had a standard version of snprintf() that can be used (maybe soon - they're adding quite a bit of C99 stuff to the toolchain).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top