I have a strange error concerning the inline
keyword, this is just a sample code I wrote:
#include <stdio.h>
#include <stdint.h>
uint8_t inline LIB_MATH_BTT_u8GetMSBSetBitPos(uint32_t args_u32Variable)
{
uint8_t local_u8MSBSetBitPos = 0;
args_u32Variable = args_u32Variable >> 1;
while (args_u32Variable != 0)
{
args_u32Variable = args_u32Variable >> 1;
local_u8MSBSetBitPos++;
}
return local_u8MSBSetBitPos;
}
int main() {
int x = LIB_MATH_BTT_u8GetMSBSetBitPos(17);
printf("%d", x);
return 0;
}
I ran this code on Visual studio 2022 and this was the result:
4
and the same code was run on Clion with toolchain from MinGW
and this was the result:
====================[ Build | untitled | Debug ]================================
"C:Program FilesJetBrainsCLion 2022.3.2bincmakewinx64bincmake.exe" --build C:UsersUserCLionProjectsuntitledcmake-build-debug --target untitled -j 12
[1/2] Building C object CMakeFiles/untitled.dir/main.c.obj
[2/2] Linking C executable untitled.exe
FAILED: untitled.exe
cmd.exe /C "cd . && C:PROGRA~1JETBRA~1CLION2~1.2binmingwbingcc.exe -g CMakeFiles/untitled.dir/main.c.obj -o untitled.exe -Wl,--out-implib,libuntitled.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
C:Program FilesJetBrainsCLion 2022.3.2binmingwbin/ld.exe: CMakeFiles/untitled.dir/main.c.obj: in function `main':
C:/Users/User/CLionProjects/untitled/main.c:6: undefined reference to `LIB_MATH_BTT_u8GetMSBSetBitPos'
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
so I am so confused why the same code was run successfully on Visual Studio 2022 but failed on Clion.
PS. the code worked successfully on Clion if I removed the inline
keyword.
2
Answers
Because that different compiler makes different decisions. Having an inline function with external linkage allows the compiler to choose from the inline version or an external non-inline non-static version of the function. Clion compiler chooses to use the external version, because you did not provide one, it fails to compile.
Consider not using
inline
. If you want to use inline, consider researching why would you want to use it and what does it exactly mean. Nowadays, compilers are smart and fast enough so we can just havestatic
functions if we want them inlined.From the C Standard (6.7.4 Function specifiers)
So as this function
has external linkage then the linker searches its external definition and does not find it.
Either you need to provide an external definition of the function (defining it with storage class specifier
extern
) or you could declare the function with internal linkage as for exampleand in this case it will be enough to use the inline definition of the function with internal linkage.