Visual Studio 2022 - How to add external header and source file to C project?

2.1k Views Asked by At

In Visual Studio 2022, for Project A I want to set up Project B that references the header (.h) and source (.cpp) files of Project A (reusing existing code). However, I don't know how the point to the existing files correctly in order for Project B to build successfully. Using #include "../unittest.h" and setting the path in Settings->C/C++->Additional Include Directories did not work (Error LNK2019, Error LNK1120). The project is a console application project.

The contents of the referencing files looks like this:

unittest.h (Project A)

#pragma once

int ret1(void);

unittest.cpp (Project A)

#include "unittest.h"

int ret1(void)
{
  return 1;
}

main.c (Project B)

#include <stdio.h>
#include "../unittest.h" // -> This doesn't seem to be enough

int main()
{
    char temp[10];
    sprintf(temp, "%d", ret1()); // Here I want to use the external function

    printf(temp);
}

Any help on how to include the external files is appreciated.


Build Logs:

Rebuild started...
1>------ Rebuild All started: Project: TestProject, Configuration: Debug x64 ------
1>TestProject.cpp
1>TestProject.obj : error LNK2019: unresolved external symbol "int __cdecl ret1(void)" (?ret1@@YAHXZ) referenced in function main
1>C:\Users\dirtl\Documents\Visual Studio 2022\Projects\TestProject\x64\Debug\TestProject.exe : fatal error LNK1120: 1 unresolved externals
1>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(1094,5): error MSB6006: "link.exe" exited with code 1120.
1>Done building project "TestProject.vcxproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
1

There are 1 best solutions below

5
Some programmer dude On

To allow for function overloading, C++ compilers uses name mangling.

That means the actual name of a C++ function is not quite what's expected, as it also have information about arguments etc.

To make a C++ function callable from C (or other compatible languages) the C++ function must be declared as extern "C":

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

int ret1(void);

#ifdef __cplusplus
}
#endif

If you modify the header file as above, and make sure that it's included in the C++ source file, then the function will not have a mangled name, and it can be called from C.