If you want both to reference the same variable, one of them should have int k;, and the other should have extern int k;
For this situation, you typically put the definition (int k;) in one .cpp file, and put the declaration (extern int k;) in a header, to be included wherever you need access to that variable.
If you want each k to be a separate variable that just happen to have the same name, you can either mark them as static, like: static int k; (in all files, or at least all but one file). Alternatively, you can us an anonymous namespace:
namespace {
int k;
};
Again, in all but at most one of the files.
In C, the compiler generally isn’t quite so picky about this. Specifically, C has a concept of a «tentative definition», so if you have something like int k; twice (in either the same or separate source files) each will be treated as a tentative definition, and there won’t be a conflict between them. This can be a bit confusing, however, because you still can’t have two definitions that both include initializers—a definition with an initializer is always a full definition, not a tentative definition. In other words, int k = 1; appearing twice would be an error, but int k; in one place and int k = 1; in another would not. In this case, the int k; would be treated as a tentative definition and the int k = 1; as a definition (and both refer to the same variable).
| description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
|---|---|---|---|---|---|
|
Learn more about: Linker Tools Error LNK2005 |
Linker Tools Error LNK2005 |
11/04/2016 |
LNK2005 |
LNK2005 |
d9587adc-68be-425c-8a30-15dbc86717a4 |
symbol already defined in object
The symbol symbol was defined more than once.
This error is followed by fatal error LNK1169.
Possible causes and solutions
Generally, this error means you have broken the one definition rule, which allows only one definition for any used template, function, type, or object in a given object file, and only one definition across the entire executable for externally visible objects or functions.
Here are some common causes for this error.
-
This error can occur when a header file defines a variable. For example, if you include this header file in more than one source file in your project, an error results:
// LNK2005_global.h int global_int; // LNK2005
Possible solutions include:
-
Declare the variable
externin the header file:extern int global_int;, then define it and optionally initialize it in one and only one source file:int global_int = 17;. This variable is now a global that you can use in any source file by declaring itextern, for example, by including the header file. We recommend this solution for variables that must be global, but good software engineering practice minimizes global variables. -
Declare the variable static:
static int static_int = 17;. This restricts the scope of the definition to the current object file, and allows multiple object files to have their own copy of the variable. We don’t recommend you define static variables in header files because of the potential for confusion with global variables. Prefer to move static variable definitions into the source files that use them. -
Declare the variable selectany:
__declspec(selectany) int global_int = 17;. This tells the linker to pick one definition for use by all external references and to discard the rest. This solution is sometimes useful when combining import libraries. Otherwise, we do not recommend it as a way to avoid linker errors.
-
-
This error can occur when a header file defines a function that isn’t
inline. If you include this header file in more than one source file, you get multiple definitions of the function in the executable.// LNK2005_func.h int sample_function(int k) { return 42 * (k % 167); } // LNK2005
Possible solutions include:
-
Add the
inlinekeyword to the function:// LNK2005_func_inline.h inline int sample_function(int k) { return 42 * (k % 167); }
-
Remove the function body from the header file and leave only the declaration, then implement the function in one and only one source file:
// LNK2005_func_decl.h int sample_function(int);
// LNK2005_func_impl.cpp int sample_function(int k) { return 42 * (k % 167); }
-
-
This error can also occur if you define member functions outside the class declaration in a header file:
// LNK2005_member_outside.h class Sample { public: int sample_function(int); }; int Sample::sample_function(int k) { return 42 * (k % 167); } // LNK2005
To fix this issue, move the member function definitions inside the class. Member functions defined inside a class declaration are implicitly inlined.
// LNK2005_member_inline.h class Sample { public: int sample_function(int k) { return 42 * (k % 167); } };
-
This error can occur if you link more than one version of the standard library or CRT. For example, if you attempt to link both the retail and debug CRT libraries, or both the static and dynamic versions of a library, or two different versions of a standard library to your executable, this error may be reported many times. To fix this issue, remove all but one copy of each library from the link command. We do not recommend you mix retail and debug libraries, or different versions of a library, in the same executable.
To tell the linker to use libraries other than the defaults, on the command line, specify the libraries to use, and use the /NODEFAULTLIB option to disable the default libraries. In the IDE, add references to your project to specify the libraries to use, and then open the Property Pages dialog for your project, and in the Linker, Input property page, set either Ignore All Default Libraries, or Ignore Specific Default Libraries properties to disable the default libraries.
-
This error can occur if you mix use of static and dynamic libraries when you use the /clr option. For example, this error can occur if you build a DLL for use in your executable that links in the static CRT. To fix this issue, use only static libraries or only dynamic libraries for the entire executable and for any libraries you build to use in the executable.
-
This error can occur if the symbol is a packaged function (created by compiling with /Gy) and it was included in more than one file, but was changed between compilations. To fix this issue, recompile all files that include the packaged function.
-
This error can occur if the symbol is defined differently in two member objects in different libraries, and both member objects are used. One way to fix this issue when the libraries are statically linked is to use the member object from only one library, and include that library first on the linker command line. To use both symbols, you must create a way to distinguish them. For example, if you can build the libraries from source, you can wrap each library in a unique namespace. Alternatively, you can create a new wrapper library that uses unique names to wrap references to one of the original libraries, link the new library to the original library, then link the executable to your new library instead of the original library.
-
This error can occur if an
extern constvariable is defined twice, and has a different value in each definition. To fix this issue, define the constant only once, or use namespaces orenum classdefinitions to distinguish the constants. -
This error can occur if you use uuid.lib in combination with other .lib files that define GUIDs (for example, oledb.lib and adsiid.lib). For example:
oledb.lib(oledb_i.obj) : error LNK2005: _IID_ITransactionObject already defined in uuid.lib(go7.obj)To fix this issue, add /FORCE:MULTIPLE to the linker command line options, and make sure that uuid.lib is the first library referenced.
Whiteha, include guard это те самые
| C | ||
|
Защищают от множественного включения одного файла. Если, например, сделать
| C | ||
|
И в этих хэдэрах подключается один и тот же заголовочныый файл, в котором не стоят инклуд гуарды, то собрать проект не выйдет.
Так что лучше их использовать всегда.
Директива #include просто подставляет содержимое файла. Так что сами представьте, что будет, если подставить содержимое одного файла дважды. Уж точно ничего хорошего 
![]()
Сообщение от Whiteha

Насколько я помню расширение подключаемых файлов может быть хоть txt, тк препроцессор работает с текстовыми файлами, а какое им задать расширение это дело традиции
Совершенно верно. Однако, следует помнить, что иные способы могут вызвать кучу недоразумений и непониманий. Собственно отсюда и пошли традиции — чтобы все друг друга понимали.
![]()
Сообщение от Kuzia domovenok

Скажи, зачем мэйкфайлы человеку пытающемуся создать первый проект из двух файлов спп в MSVS? Инклуд стражи он уже использовал не там где надо.
То, что MSVS сама генерирует мэйкфайл или что-либо подобное не значит, что его нет или что этого человека можно обманывать, говоря о линкере как о всеумеющей тулзе. Это не так.
Не по теме:
![]()
Сообщение от Kuzia domovenok

Мне впадлу было.
Я так посмотрю с Вами часто такое.
Привет!
Возникла проблема в VS 2017 с ошибкой линкования файлов (LNK2005), прикреплю скриншоты для наглядности.
В проекте 3 файла:
- MyForm.h — файл самой формы C++CLI, здесь я делаю #include «source.cpp», что скорее всего и падает, также здесь использую методы взаимодействия с формой типа openFileDialog и т.д.
spoiler


- Source.cpp — основной скрипт на 1.3к строк, мне нужно в MyForm.h вызвать вызвать функцию void solve() {…}, которая работает только в пределах стандартных библиотек и самого Source.cpp, не вызывая ничего «изнутри», для простоты все закомментировал и во всем файле оставил:
void solve() { // }spoiler

- MyForm.cpp — нужен только для определения точки входа в приложение, там ничего не происходит.
spoiler

Возможно напутал с пространством имен или подключением, но если создать заголовок H1.h, где написать:
#include "source.cpp"
void solve();
— тоже не рабит(
В гугле нашел информацию про переопределение в нескольких файлах одной и той же функции, но у меня всего 1 файл с определением и подключаю его всего 1 раз;
Если мысль, что ошибка из-за того, что подключаю как-то так: Source.cpp -> MyForm.h -> MyForm.cpp…
Подскажите, как правильно!
Problem
This technote explains why the error might occur when IBM® Rational® Test RealTime™ instruments a Microsoft® Foundation Class (MFC) application. This application uses dynamic link libraries (DLLs) of the Application Framework Extensions (AFX) .
Symptom
During the instrumentation of an MFC application with AFX DLLs the following error occurs at link time.
The full error message is as follows:
error LNK2005: "void * __cdecl operator new(unsigned int)" already defined
Cause
The Target Deployment Port contains a redefinition of the two C++ functions new and
delete. As a consequence the Target Deplyment Port can now detect memory leaks.
By default the Target Deployment Port on Windows tries to link the application statically. This is not possible with applications that use MFC classes and the AFX DLLs, because it results in a double definition of the new operator.
Resolving The Problem
Modify the settings for the runtime analysis node or the component testing for C++ node. Add the following flags:
Configuration Settings > Build > Compiler > Preprocessor Options: -D_AFXDLL -MD
Configuration Settings > Build > Linker > Link Flags: /nodefaultlib:msvcrt
[{«Product»:{«code»:»SSSHUF»,»label»:»Rational Test RealTime»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»—«,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»2003.06.00;2003.06.01;2003.06.12;2003.06.13;2003.06.15;7.0;7.0.0.1;7.0.5″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]
Historical Number
152827401
Hi again,
I am getting this linker error below and could not quite figure out why. It seems that the linker is saying I declared my static class variable OptionFactory EuropeanCall::MyFactory mutliple times. Perhaps it is the way I am declaring it inside VanillaOptions.h? I am rather new to C++ so it is not obvious to me.
Thank you for any help!
Linking…
OptionFactory.obj : error LNK2005: «public: static class OptionFactory<class BaseOption,class EuropeanCall> EuropeanCall::MyFactory» (?MyFactory@EuropeanCall@@2V?$OptionFactory@VBaseOption@@VEuropeanCall@@@@A) already defined in MCMain.obj
VanillaOptions.obj : error LNK2005: «public: static class OptionFactory<class BaseOption,class EuropeanCall> EuropeanCall::MyFactory» (?MyFactory@EuropeanCall@@2V?$OptionFactory@VBaseOption@@VEuropeanCall@@@@A) already defined in MCMain.obj
InitializeOptionFactory.obj : error LNK2005: «public: static class OptionFactory<class BaseOption,class EuropeanCall> EuropeanCall::MyFactory» (?MyFactory@EuropeanCall@@2V?$OptionFactory@VBaseOption@@VEuropeanCall@@@@A) already defined in MCMain.obj
C:tmpCPPCalvinMC_VS_2005MCDebugMC.exe : fatal error LNK1169: one or more multiply defined symbols found
//OptionFactory.h
//Creates new option based on the choice user made from menu
#ifndef OPTIONFACTORY_
#define OPTIONFACTORY_
#include <string>
template <class OptionType>
class OptionFactoryTemplate
{
public:
OptionFactoryTemplate(){};
virtual ~OptionFactoryTemplate(){};
virtual OptionType* CreateOption()=0;
};
template <class OptionType, class NewOption>
class OptionFactory : public OptionFactoryTemplate<OptionType>
{
public:
OptionFactory(){};
virtual ~OptionFactory(){};
virtual OptionType* CreateOption();
};
#endif
//BaseOption.h
//Define attributes and functions of a base option
#ifndef BASEOPTION_
#define BASEOPTION_
#include <map>
#include <OptionFactory.h>
class BaseOption
{
private:
double Strike, Expiration, RiskFreeRate, Price, Delta, Gamma, Vega, Theta;
public:
BaseOption(); //Constructor
virtual ~BaseOption(){}; //Virtual destructor
typedef OptionFactoryTemplate<BaseOption> BaseOptionFactory; //Baseoption factory
};
//Declare the global static option factory map
static std::map<std::string, BaseOption::BaseOptionFactory *> OptionFactoryMap;
#endif
//VanillaOptions.h
//Define all vanilla options, defined as single asset, non-path dependent options
//Includes : European Call/Put, Digial Call/Put on a single underlying
#ifndef VANILLAOPTIONS_
#define VANILLAOPTIONS_
#include <BaseOption.h>
#include <OptionFactory.h>
class EuropeanCall : public BaseOption
{
private:
BaseAsset UAsset; //Underlying asset
public:
EuropeanCall();
~EuropeanCall(){};
static OptionFactory<BaseOption, EuropeanCall> MyFactory;
virtual BaseAsset GetUAsset() const;
};
OptionFactory<BaseOption, EuropeanCall> EuropeanCall::MyFactory;
#endif
//MCMain.cpp
#include <MonteCarlo.h>
#include <UserInterface.h>
#include <VanillaOptions.h>
#include <iostream>
void main()
{
UserInterface ui; //User interface object
std::string OptionChoice;
//Output user interface to pick option choice until user chooses to stop
do {
OptionChoice = ui.MenuPickOption();
} while (ui.AskKeepGoing());
}
Я пытался решить проблему, связанную с модулями компиляции.
Я получаю ошибку
1>frtinvxml.obj : error LNK2005: "struct repFieldInfo det_rep_info" (?det_rep_info@@3UrepFieldInfo@@A) already defined in Frtinv.obj
1>frtinvxml.obj : error LNK2005: "struct repFieldInfo frt_rep_info" (?frt_rep_info@@3UrepFieldInfo@@A) already defined in Frtinv.obj
1>frtinvxml.obj : error LNK2005: "struct FormToolbar * tb" (?tb@@3PAUFormToolbar@@A) already defined in Frtinv.obj
1>frtinvxml.obj : error LNK2005: "struct tagDATE_STRUCT dateFrom" (?dateFrom@@3UtagDATE_STRUCT@@A) already defined in Frtinv.obj
... (It goes on for every variable and method in the header...)
Это единственная ошибка, которую я получаю. Вот включения для каждого соответствующего класса, участвующего в порядке от самого высокого на дереве до самого низкого …
***Frtinv.hxx***
#pragma once
#include <voyage.ddh>
#include <vsched.ddh>
# ...
struct frtinvType : public frtinv_type
{
int fixCarSeq;
...
…
***frtinv.cxx***
//#define _IN_MAIN_
#include <decisionTable.h>
...
#define RINDEX 2
#define LINDEX 2
#define PINDEX 0
BOOL s_fNeedSaveAfterDelete = FALSE;
static int rateCnt = RINDEX, lumpCnt = LINDEX, pcntCnt = PINDEX;//------------------------------------------------------------------------
int getPortcar(char *vslCode, int voyNo, int portCallSeq, int berthSeq, int seq, portcar_type *pret)
...
…
***frtinvxml.h***
#define _IN_MAIN_
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <zdb.hxx>
#include <opr32.h>
#include <voyage.ddh>
#include <frtinv.ddh> <------ Tried to add these two to the solution, that failed.
#include <frtinv.hxx> <------
void exitGracefully();
std::list<voyage_type> getVoyages();
…
***frtinvxml.cpp***
#include "frtinvxml.h" <------ taking everything from frtinvxml.h
void main(int argc, char *argv[]) {
InitWinLib (10, 8);
...
Моя проблема связана с тем, что даже если я помещаю файлы в одну папку / решение, я не могу заставить их не определять себя дважды. Даже при использовании ключевого слова Pragma Once. Я также попытался использовать старую школу #define, не включайте, если она уже существует … это тоже не сработало.
Есть ли у вас какие-либо решения или рекомендации?
-1
Решение
#pragma once предотвращает многократное включение заголовка в одну единицу компиляции — в данном случае файл .obj — и ошибка прямо заявляет, что frtinvxml.obj определяет то, что уже было определено в Frtinv.obj. Два отдельных объекта. Два отдельных сборника.
once отлично работал в случае Frtinv.obj и снова в случае frtinvxml.obj. Оба имеют одно и то же определение, иначе источники не были бы скомпилированы. К сожалению, компоновщик пытается поместить оба объекта в один и тот же вывод.
Два решения для этого, в зависимости от того, как переменная будет использоваться, но для обоих не делать объявления в заголовках. Это почти всегда плохо кончается.
Определение:
extern struct repFieldInfo det_rep_info;
в соответствующем заголовке. extern говорит компилятору это где-то det_rep_info будет объявлено, и компиляция должна продолжать использовать этот внешний det_rep_info,
В файле cpp, frtinvxml.cpp, Frtinv.cpp или в каком-то третьем cpp, который содержит общие данные, объявите
struct repFieldInfo det_rep_info;
Затем сделайте то же самое с остальными тремя дублирующимися переменными.
Точно, где поместить эти переменные, зависит от личного вкуса, выбора и стандарта кодирования. Скомпилируйте этот файл и свяжите его с другими файлами .obj, чтобы каждый мог получить доступ к переменной.
Объявляет:
static struct repFieldInfo det_rep_info;
в каждом файле cpp, который требует этого. Повторите для всех необходимых переменных. static гарантирует, что каждый det_rep_info виден только в определенной области. В этом случае один блок компиляции. Там на самом деле немного тонкости, так что читать документацию Чтобы убедиться static подходит для вас.
Вы можете поместить объявление в заголовок, и каждый включающий заголовок получит свою собственную копию, но важно отметить, что каждый включающий заголовок получит копию, хотят они этого или нет. Не принимайте это решение за других людей. Объявите переменную в нужных файлах cpp. Компилятор поймает его, если вы пропустите один.
4
Другие решения
Других решений пока нет …
15 ответов
Если вы внимательно прочитали ошибку компоновщика и примените некоторые знания, вы можете попасть туда сами:
Компонент связывает несколько скомпилированных объектов и библиотек вместе, чтобы получить двоичный файл.
Каждый объект/библиотека описывает
- какие символы он ожидает присутствовать в других объектах
- какие символы он определяет
Если два объекта определяют один и тот же символ, вы получаете именно эту ошибку компоновщика. В вашем случае как mfcs80.lib, так и MSVCRT.lib определяют символ _DllMain @12.
Как избавиться от ошибки:
- узнать, какая из двух библиотек вам действительно нужна
- узнайте, как рассказать компоновщику не использовать другой (используя, к примеру, отзыв от Джеймса Хопкина).
xtofl
05 дек. 2008, в 11:19
Поделиться
У меня было такое же сообщение об ошибке, но ни один из ответов здесь не разрешил для меня.
Поэтому, если вы столкнулись с этой проблемой при создании DLL-проекта, который использует MFC, его можно решить, введя следующую строку:
extern "C" { int _afxForceUSRDLL; }
в файл cpp, где DllMain определен. Затем используется ваша собственная реализация DllMain, а не одна из dllmain.obj.
Когда мы пытаемся использовать библиотеку MFC, мы обязательно включим afx.h напрямую или косвенно, то MFC (afx.h) сообщает компоновщику, чтобы найти символ __afxForceUSRDLL и поместите этот объект, который содержит __afxForceUSRDLL в программу, поэтому линкер выполняет поиск и помещает dllmodule.obj в наш потому что __afxForceUSRDLL определяется в dllmodule.cpp.
Это общий сценарий. Когда мы хотим использовать наш собственный DllMain в mfc dll project, компоновщик жалуется, что есть два DllMain, один в наш код, один в Dllmodule.obj.
Итак, нам нужно сказать компоновщику, чтобы добавить наш dllmain.obj для __afxForceUSRDLL. Поэтому нам нужно определить __afxForceUSRDLL в нашем собственном файле cpp, где определен наш собственный DllMain, тогда компоновщик будет игнорировать mfcs dllmodule.obj и видеть только один DllMain и никогда не жалуется.
Источник: http://social.msdn.microsoft.com/Forums/en-US/0d78aa6b-1e87-4c01-a4a7-691335b7351a/how-to-build-mfc-application-dll-in-visual-c-2010
Constantin
12 нояб. 2013, в 14:33
Поделиться
Если вы определяете свой собственный DllMain, в настройках вашего проекта вам нужно установить «Использовать MFC» в «Свойства конфигурации/Общие» для «Использовать стандартные библиотеки Windows».
Вы должны сделать чистую перестройку после ее изменения.
James Hopkin
05 дек. 2008, в 10:40
Поделиться
Для меня прямая причина была действительно отсутствующей ссылкой на символ _afxForceUSRDLL, но косвенной причиной было отсутствие определения макроса _USRDLL. Он определяется по умолчанию мастером VC, но иногда разработчики стирают его ошибочно.
Вот несколько слов.
Ofek Shilon
06 май 2015, в 05:49
Поделиться
В моем проекте я смог решить эту проблему, добавив mfcs80.lib и msvcrt.lib в качестве дополнительных зависимостей в настройках проекта. «Дополнительные зависимости» можно найти в Linker → Input.
В конфигурации отладки, которая должна быть mfcs80d.lib и msvcrtd.lib соответственно.
Кстати, я работаю с Visual Studio 2010, поэтому в моем случае MFC lib называется mfc100.lib.
Я не уверен, почему это сработало. Нет необходимости добавлять эти файлы lib в качестве дополнительных зависимостей, потому что я уже установил «Использование MFC» в «Использовать MFC в общей DLL». Я предполагаю, что, указав эти библиотеки в качестве дополнительных зависимостей, они связаны в другом порядке.
Это решение более или менее совпадает с тем, которое предлагается на сайте Microsoft: http://support.microsoft.com/kb/148652, за исключением того, что мне не нужно вводить все в поле «Игнорировать конкретные библиотеки по умолчанию».
vmb100
05 июль 2012, в 13:59
Поделиться
Для всех тех, кто испытывает эту ошибку в проектах ATL (в основном при попытке добавить поддержку MFC), вот решение, которое я нашел после нескольких дней разочарования!
Прежде всего, эта ссылка была для меня более полезной, чем все остальные. Он указал мне в правильном направлении. Проблема возникает, если по какой-то причине «сгенерированные файлы» (содержащие прокси-сервер и код-заглушки, так же как и типы) были удалены и прочитаны в проекте. Это заставляет Visual Studio добавлять их в неправильном порядке!
Обычно вы сначала сталкиваетесь с ошибкой «ATL требует компиляции С++», но вы можете исправить это, отключив параметр Yc/Yu (предварительно скомпилированные заголовки) для этого файла.
Что вы должны сделать дальше, это разгрузить проект и отредактировать его. Найдите группы товаров, которые определяют порядок сборки и включают порядок (ClCompile и ClInclude). Проверьте их порядок и настройки.
Компиляторы должны отображаться в следующем порядке:
-
dllmain.cpp(сCompileAsManagedустановлено значениеfalseиPrecompiledHeaderосталось пустым). - Источник библиотеки (
MyLib.cpp, содержащийDllCanUnloadNowи т.д.) - Код прокси-сервера (
MyLib_i.c; с теми же настройками, что иdllmain.cpp) -
stdafx.cpp(сPrecompiledHeaderустановлено значениеCreate) - Все остальные исходные файлы библиотеки (фактическое содержимое библиотек)
-
xdlldata.c(с теми же настройками, что иdllmain.cpp)
Затем заказы должны быть упорядочены следующим образом:
-
dllmain.h -
MyLib_i.h -
Resource.h -
stdafx.h -
targetver.h - … (фактические заголовки библиотек)
-
xdlldata.h
Фиксирование порядка сборки зафиксировал мой проект, и я смог создать новую чистую сборку.
Carsten
13 янв. 2015, в 10:19
Поделиться
Идентификатор базы знаний MSDN Q148652.
http://support.microsoft.com/kb/148652
Причина:
Visual С++ компилирует исходные файлы в алфавитном порядке и передает скомпилированные объектные файлы в компоновщик в алфавитном порядке.
Если компоновщик сначала обрабатывает DLLDATAX.OBJ, исходный код ссылается на DllMain, который компоновщик загружает из MSVCRTD.LIB(dllmain.obj).
Затем компоновщик обрабатывает объектный файл, скомпилированный из файла С++, который содержит #include «stdafx.h», который ссылается на символ
__afxForceUSRDLL, который компоновщик загружает из MFC42D.LIB(dllmodul.obj). Этот объектный модуль также содержит реализацию для DllMain,
вызывая конфликт.
Bill
06 сен. 2013, в 07:38
Поделиться
В моем случае у меня была проблема с директивами препроцессора.
По какой-то причине _USRDLL был определен, когда он не должен был быть.
Чтобы проверить это, перейдите в меню Project , выберите Project Properties , затем выберите фрагмент Configuration Properties → Preprocessor .
Здесь будут найдены директивы препроцессора.
joan
19 авг. 2014, в 19:31
Поделиться
Просто #undef _USRDLL перед включением afx.h или даже лучше отредактируйте конфигурацию проекта и удалите макрос.
Это обычная конфигурация для DLL расширения MFC: Настройки сборки для MFC DLL
mgruber4
02 дек. 2015, в 23:37
Поделиться
У меня очень похожая проблема. [mfcs110d.lib(dllmodul.obj): ошибка LNK2005: _DllMain @12 уже определена в MSVCRTD.lib(dllmain.obj)], и решение было добавить mfcs110d.lib в дополнительные зависимости
joseAndresGomezTovar
24 апр. 2014, в 08:32
Поделиться
Я лично избавился от этой ошибки следующим образом: проект с правой кнопкой мыши в Solution Explorer, выбранном Properties из всплывающего меню, нажал вкладку Linker и добавил mfcs71ud.lib в Additional Dependencies. Если вы используете Visual Studio 2005, это должно быть «80» вместо «71» и т.д.
izogfif
20 апр. 2013, в 21:34
Поделиться
Убедитесь, что вы включили «Stdafx.h» в начало каждого файла .cpp. Я получал ту же ошибку и имел единственный .cpp файл, который вообще не включал этот заголовок. Добавление #include решило проблему.
Matt Davis
10 июнь 2016, в 04:03
Поделиться
Объявите mfc80ud.lib и mfcs80ud.lib в поле Additional Dependancies в Project Properties -> Linker Tab -> Input of Visual Studio, чтобы устранить проблему.
Avishek Bose
09 окт. 2015, в 04:22
Поделиться
Я нашел это, что помогло мне:
http://support.microsoft.com/kb/148652
В основном порядок компоновщика был неправильным. CRT libs связывались перед библиотекой MFC. Оказывается, библиотеки MFC должны были быть связаны FIRST, а затем библиотеки CRT могли быть связаны.
Yucko Microsoft!!
C Johnson
22 окт. 2014, в 17:06
Поделиться
Я нашел решение здесь
Порядок компоновки библиотек Visual Studio 2010
это:/FORCE: MULTIPLE
в вариантах компоновщика
Мне пришлось смешивать ATL и MFC вместе, чтобы использовать
[module (name = «mymodule» )]; в приложении MFC вместе с ключевым словом «__hook»
Serov Danil
23 май 2014, в 15:33
Поделиться
Ещё вопросы
- 0Вывод на основе найденных максимальных ключевых слов
- 1Альтернатива символической ссылке / proc / PID / exe для получения полного пути других процессов через PID
- 1Вычисление координаты пересечения между линиями и окружностью и степени линии на холсте
- 0При назначении нового массива из существующего массива php показывает только последнее значение массива
- 0Ошибка в signal.c при компиляции qemu-xen
- 0Angular JS: встроенный стиль со связанным значением работает на Mac, а не на Windows
- 0кеширующий элемент dom с использованием пространства имен
- 1использовать await внутри функции Array.map
- 0угловая маршрутизация теряет цвет
- 0preg_replace оставляет два пробела
- 1Entity Framework использует проекцию для быстрой загрузки некоторых элементов с нулевой проверкой
- 1Как отличить подобные пользовательские элементы управления в ViewModel?
- 0Ошибка компиляции g ++
- 1XPath не ожидал результата с lxml
- 0Как определить, равен ли ключ массива другому значению массива в PHP
- 1Передача данных модели из представления в контроллер приводит к ошибке
- 1Проверить, что путь пуст в glob?
- 0элемент формы добавлен с jquery не выполняет правильное действие
- 1Python Twisted в PB, вызов функции клиентского сервера
- 1Google maps LatLng не число
- 1Rx: разница между CurrentThreadScheduler и ImmediateScheduler
- 0Ошибка Urlmanager и Controller :: createUrl в YII
- 0Загрузите сгенерированный PDF с проблемой памяти нескольких страниц
- 0Как получить читаемую строку из двоичных данных в PHP?
- 1nightwatch: сбой обратного вызова в waitForElementPresent
- 1Graphql: должен предоставить строку запроса
- 0Проблема с функцией Показать / Скрыть в jQuery. Перейти к началу страницы
- 0ngShow фокусируется на вводе данных в мобильном Safari
- 0Как отфильтровать несколько столбцов с предложением IN, используя AND
- 0Исходный код шифрования AES
- 1Не удается импортировать замороженный график после добавления слоев в модель Keras
- 1Как создать правило сонара для анализа пользовательского файла XML в Java?
- 1Понимание рекурсивного асинхронного вызова в JavaScript
- 0Как настроить Wampserver для подключения к серверу mssql с помощью PDO?
- 1Использование C # HttpClient для входа на веб-сайт и получения информации с другой страницы
- 1проблемы автоматизации ПЯТОГУИ ГИМП
- 0Как перебрать все ключи кроме одного в руле?
- 1Как предотвратить неожиданное падение моего приложения, принудительное закрытие при использовании данных JSON и обработать исключение вместо этого?
- 0Что эквивалентно SELECT в mongodb?
- 0Как применить темы к HTML внутри метода append ()
- 1Генерация 1000 случайных чисел от 13 до 100
- 0Управление: (символ двоеточия) в ответе JSON для AngularJS
- 0Выделение переменного количества объектов в стеке в C ++
- 0Повторяйте вложенный цикл, если результат не тот, который я хотел
- 0Отображение тега div в текстовом поле
- 1Как моя функция может принимать CSV-файлы в качестве входных данных?
- 1WinAPI MoveWindow функция не работает для некоторых окон
- 1манипулирование яркостью в цветовом пространстве YUV
- 0Не знаю, какой плагин JQuery использовать
- 0проверить строку с регулярными выражениями для некоторого значения
Today I got “error LNK2005: _DllMain@12 already defined in msvcrtd.lib” while linking some C++ CLI project with MFC support in MS Visual Studio 2013. As described in A LNK2005 error occurs when the CRT library and MFC libraries are linked in the wrong order in Visual C++A LNK2005 error occurs when the CRT library and MFC libraries are linked in the wrong order in Visual C++ article, I added /verbose:lib linker option:
![]()
and got the following linker output:
1> Finished searching libraries 1> 1> Searching libraries 1> Searching C:Program Files (x86)Microsoft Visual Studio 12.0VCatlmfclibmfc120ud.lib: 1> Searching C:Program Files (x86)Microsoft Visual Studio 12.0VCatlmfclibmfcs120ud.lib: 1>mfcs120ud.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in msvcrtd.lib(dllmain.obj) 1> Searching C:Program Files (x86)Microsoft Visual Studio 12.0VClibmsvcrtd.lib: 1> Searching C:Program Files (x86)Windows Kits8.1libwinv6.3umx86kernel32.lib:
Obviously DllMain is defined twice in MFC and VC Runtime but that is all the information we can extract from here, so I did some further experimentations and finally removed couple files containing AFX_MANAGE_STATE(AfxGetStaticModuleState()) from the project, and it solved the problem. Looks like this AFX_MANAGE_STATE affects something that causes this linker error.
Also I got some annoying warning about HIMAGELIST “warning LNK4248: unresolved typeref token (01000018) for ‘_IMAGELIST’; image may not run”. It is not clear what should I do with it, but at least useful links:
- Linker Tools Warning LNK4248
- warning LNK4248: unresolved typeref token (01000017) for ‘_TREEITEM’; image may not run