Undefined Reference to a function

后端 未结 5 771
说谎
说谎 2020-12-18 10:34

I\'m using Linux and I have the following files:

main.c, main.h
fileA.c, fileA.h
fileB.cpp, fileB.h

The function F1() is decla

相关标签:
5条回答
  • 2020-12-18 10:46

    To be able to call a c++ function from c source code you neeed to give the appropriate linkage specification.

    The format for specifying linkage specification is

    extern "type_of_Linkage" <function_name>
    

    So in your case, you should be using:

    extern "C" void F1();
    
    0 讨论(0)
  • 2020-12-18 10:52

    perhaps, use

    extern "C" void F1();
    
    0 讨论(0)
  • 2020-12-18 10:56

    If you're really compiling fileA.c as C, not C++, then you need to make sure that the function has the proper, C-compatible linkage.

    You can do this with a special case of the extern keyword. Both at declaration and definition:

    extern "C" void F1();
    extern "C" void F1() {}
    

    Otherwise the C linker will be looking for a function that only really exists with some mangled C++ name, and an unsupported calling convention. :)

    Unfortunately, whilst this is what you have to do in C++, the syntax isn't valid in C. You must make the extern visible only to the C++ code.

    So, with some preprocessor magic:

    #ifdef __cplusplus
    extern "C"
    #endif
    void F1();
    

    Not entirely pretty, but it's the price you pay for sharing a header between code of two languages.

    0 讨论(0)
  • 2020-12-18 11:00

    fileA.c needs to also include fileA.h I believe.

    0 讨论(0)
  • 2020-12-18 11:09

    fileA.c can't include fileB.h (via fileA.h) because the C compiler doesn't know what extern "C" means, so it complains that it sees an identifier before a string. don't try to include fileB.h in fileA.c or fileA.h. its not needed

    0 讨论(0)
提交回复
热议问题