c++c++20

The function that has not been called still reports an error in the link stage,


but the same code in the teaching demonstration runs without reporting an error. main.cpp

#include <iostream>

void Log(const char* message);

static int Multiply(int a, int b) {
    Log("Multiply");
    return a * b;
}

int main() {
    // std::cout << Multiply(5,8) << std::endl;
    std::cout << std::cin.get();
}

log.cpp

#include <iostream>

void Loge(const char* message) {
    std::cout << message << std::endl;
}

As you can see, The multiply function calls the function log. But the function multiply has "static" which means it doesn't been used in any other cpp files. And the only call of this function is been //(annotated). So the function multiply is never used.(Clion also reports this) So, my teacher click build and no error in his vs2017. He said this log function is never used. So the link stage doesn't check this name. But I get a error in my CLion 2024.(Of course I know "Loge" is not same as "Log") Why?

search on the internet The reason


Solution

  • Ignoring unused function depends on the compiler and how the project is structured, MSVC (visual studio) accepts it, which is likely what your instructor uses.

    While gcc (and mingw which clion uses) refuses it at link time and can be convinced to accept it by adding the flag

    -Wl,--unresolved-symbols=ignore-in-object-files
    

    to force the linker to ignore missing symbols (which is not recommended) or

    -ffunction-sections -fdata-sections -Wl,--gc-sections
    

    to get the compiler to put every function in a section and remove unused sections, this can increase or decrease binary size and may drop unused static objects in other translation units resulting in weird non-conformant behavior in some cases (so also not recommended)