Main Content

Resolve Build Error: Multiple Redefinition Linker Errors

Issue

When publishing a MATLAB® interface to a C++ library, MATLAB compiles and builds C/C++ code. If the library files or supporting source files contain multiple definitions of a construct (such as a function, method, or variable), a linker error occurs when you publish the interface.

The linker error message text depends on your platform.

PlatformLinker Error Message

Microsoft® Visual Studio®

Message contains error LNK2005 or LNK1169 and might include this phrase regarding a construct in an .obj file: already defined.

MinGW®
Linux® gcc

Message includes this phrase regarding a construct: multiple definition.

macOS Xcode

Message includes this phrase regarding a construct: duplicate symbol.

Possible Solutions

The multiple definition issue can have several possible causes and solutions, including:

  • Variable in header file that is included in multiple source files — If you define a variable in a header file, verify that the header file is included in only one source file.

  • Non-inline function in header file that is included in multiple source files — If you define a function that is not inline in a header file, verify that the header file is included in only one source file.

  • Member function definition outside class declaration — If you define a member function in a header file, verify that the member function exists within the class declaration.

For more possible causes and solutions, see this Microsoft article: Linker Tools Error LNK2005.

For example, suppose that a header file in your library declares method getVal on class A:

// h.hpp
class A {
public:
    A() {};
    int getVal();
};

Your library consists of two source files, file1.cpp and file2.cpp. Each file contains a definition of the getVal method. In file1.cpp:

// file1.cpp
#include "h.hpp"
int A::getVal() {
    return 5;
}

In file2.cpp:

// file2.cpp
#include "h.hpp"
int A::getVal() {
    return 10;
}

You can have only one definition for getVal. Republish your interface with either file1.cpp or file2.cpp, not both.