Search code examples
c++cwindowssystem

C++: How to resolve implicit declaration compile error?


I'm learning C++. With this super basic example, I'm able to perform a PowerShell command.

#include <stdio.h>
int main() {
   system("powershell.exe New-Item -ItemType File -Name cpp_test");
   return 0;
}

When compiled in Debian, I get the following (non fatal?) error message:

$ x86_64-w64-mingw32-gcc test.c -o test.exe

test.c: In function ‘main’:
test.c:3:4: warning: implicit declaration of function ‘system’ [-Wimplicit-function-declaration]
    system("powershell.exe New-Item -ItemType File -Name cpp_test");
    ^~~~~~

I looked up the implicit declaration error but don't quite understand how it applies to my example. Can someone try explaining it to a five yr old...

Revised, test.cpp:

#include <cstdlib>
int main() {
   system("powershell.exe New-Item -ItemType File -Name cpp_test");
   return 0;
}

Solution

  • The C function system is declared in the C++ header <cstdlib> (or in C in the header <stdlib.h>)

    So if your program is a C++ program then substitute the header <stdio.h> that is not used in your program for

    #include <cstdlib>
    

    Otherwise write

    #include <stdlib.h>
    

    Supporting the backward compatibility the compiler assumes that the function declared somewhere else and it is unable to check whether the call of the function is correct.