linking error for not being able to link header file to cpp file correctly

后端 未结 2 1553
北荒
北荒 2021-01-26 03:35

I have two projects in one solution. When I try to access a function of one project\'s from another one I get error LNK2001: unresolved external symbol. But the lin

相关标签:
2条回答
  • 2021-01-26 03:59

    It is the role of the linker to resolve unknown symbols.

    Thus if projet A uses methods from projet B defined in the cpp file, you need to link A against B.

    As stated, it would be fine to have more information about both projects, IDE (visual???)...

    0 讨论(0)
  • 2021-01-26 04:04

    If you define the function in the header file, the compiler will see the function implementation when you build the .exe project and compile a copy of the function code directly into your .exe project. When it is the linker's turn during the build, nothing is missing so the linker is happy and you won't get an error message.

    If you define the function in the .cpp file, the compiler will not see the function implementation. It will thus put a reference to the function (i.e. the external symbol) that needs to be resolved later on when it is the linker's turn during the build. To make the linker "see" the external symbol, you need to link your .exe project against your .lib project. Once you have established this link dependency, the linker will be able to find the external symbol and resolve the reference to the function that was earlier generated by the compiler. Because you have a .lib project, which is a static library project, the linker resolves the symbol by grabbing the code for the function from the .lib file and places a copy of the code into your .exe file.

    So much for the theory. Now the simplest way to make your .exe project link against your .lib project probably is by adding a reference:

    • In the .exe project's settings, select the section named "Common Properties" at the top of the section list.
    • You should now see a list of references that the .exe project has. The list is probably empty.
    • Click the "Add new reference" button at the bottom of the dialog and add the .lib project as a reference
    • When you select the new reference in the list of references you will see a set of properties for that reference. Make sure that the property called "Link Library Dependencies" is set to true. This will cause the .lib project to be added automatically as an input to the linker when you build the .exe project.

    If you build your .exe project, the linker error should now be gone.

    Incidentally, by adding the project reference you have also told Visual Studio to build the two projects in the correct order if you build the entire solution: First the .lib project, then the .exe project.

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