Error lnk2005 fortran

Copied from the buildlog.htm and identical to the output in visual studio: Druckzyklen.lib(Main_Berechnung.obj) : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:LBR' specification Druckzyklen.lib(Main_Berechnung.obj) : error LNK2005: _powf already defined in libmmt.lib(powf_iface_c99.obj)...

Hello,

I have a Visual Studio Solution which should create a DLL. It consists of a Fortran part and a part written in C++ in two seperate projects. The Fortran Source Code is calling C++ functions. When I try to build it, I get the following message:

error LNK2005: _powf already defined in libmmt.lib(powf_iface_c99.obj)

From my understanding this means that the powf is defined more than one time, therefore it is not clear which function really should be called.

Some more information:

— When I build it on «Release» it works.

— I was reading that this error can be cause of different floating point models. So I made sure that those models are set to the same option in every project (Fortran and C++). https://software.intel.com/en-us/forums/intel-c-compiler/topic/622985

— In the C++-projects I included the librarys <cmath> or <math.h> but got the same error on both includes.

— Both are built with the same Runtime Library. Tried out a couple of possible combinations too.

I would be glad for any help

  • Intel® Fortran Compiler

  • All forum topics


  • Previous topic

  • Next topic

13 Replies

Please provide the complete transcript of the attempted linking step. Around the single line that you showed, there would have been a few lines that showed the source of the other location(s) of the previously defined symbol, such as another library name.

Once that information becomes available, one would have to look at the full linking command line, or the selected options in VS for the project. If you are able to provide the build log, that would help, too.

Copied from the buildlog.htm and identical to the output in visual studio:

Druckzyklen.lib(Main_Berechnung.obj) : warning LNK4075: ignoring ‘/EDITANDCONTINUE’ due to ‘/OPT:LBR’ specification
Druckzyklen.lib(Main_Berechnung.obj) : error LNK2005: _powf already defined in libmmt.lib(powf_iface_c99.obj)
Druckzyklen.lib(factor_correct.obj) : error LNK2005: _powf already defined in libmmt.lib(powf_iface_c99.obj)
   Creating library d:DevelopmentE2E2_DLLDebugE2_0306.lib and object d:DevelopmentE2E2_DLLDebugE2_0306.exp
DebugE2_0306.dll : fatal error LNK1169: one or more multiply defined symbols found

You have shown the output only, not the commands used for the build. Zip the buildlog.htm and attach it here. We’d also need to see the C++ project settings.

Perhaps try this — set the Fortran project property Fortran > Libraries > Use Runtime Library to «Multithread DLL» (for the Release configuration) or «Multithread Debug DLL» for the Debug configration.

The buildlog is attached to this mail.

The list of properties is very long, are there settings that are particularly important?

I already tried it out to change the runtime librarys, without any success.

You are linking in several libraries, and the run-time library settings in all of them have to match. I see you are already using /libdir:noauto on your own project, which is good. But if the other libraries were built in C++ with conflicting options, that can be a headache.

The first thing I would do is, from a Fortran command prompt, do a «dumpbin -directives» on each of the .lib files to see which libraries they want. You would then set the executable project property Linker > Input > Ignore all default libraries to Yes. Then you’ll have to name all of the required libraries (such as libifcoremd) in the Linker > Additional Dependencies property. This will take some effort to sort out.

Thank you so much, now it works.

But to be honest I haven’t carried out all your suggestions from above yet. I started switching the property «Ignore all default libraries» to Yes and tried to compile, and then it works. Although some of the linked projects still have it on «No». So now it is kinda «lucky combination» of the project settings, that works fine in this case.

I want to understand exactly what happens here and tried to do such a dumpbin-directive, but so far I have not figuered it out how to do this. Can you give me an advice? I tried to execute it via the comand line and the ifort.exe, but this did not work.

Thanks a lot in advance.

There is a space before -directives. Looks like this:

D:Projects>dumpbin -directives t.lib
Microsoft (R) COFF/PE Dumper Version 14.14.26433.0
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file t.lib

File Type: LIBRARY

   Linker Directives
   -----------------
   -defaultlib:ifconsol
   -defaultlib:libifcoremt
   -defaultlib:libifport
   -defaultlib:libmmt
   -defaultlib:LIBCMT
   -defaultlib:libirc
   -defaultlib:svml_dispmt
   -defaultlib:OLDNAMES

  Summary

          B9 .drectve
          10 .text

By default, when you compile a source the compiler inserts instructions for the linker (directives) that ask the linker to link to a set of libraries (which it then finds through its normal search path). In this example you can see that it wants the static library versions of the Intel Fortran and Microsoft C++ libraries. Your program may not need all the libraries listed.

Now I’ll recompile the source and specify /libs:dll (which is the default for new projects in Visual Studio):

Dump of file t.lib

File Type: LIBRARY

   Linker Directives
   -----------------
   -defaultlib:ifconsol
   -defaultlib:libifcoremd
   -defaultlib:libifportmd
   -defaultlib:libmmd
   -defaultlib:MSVCRT
   -defaultlib:libirc
   -defaultlib:svml_dispmd
   -defaultlib:OLDNAMES

  Summary

          BB .drectve
          10 .text

The library names have switched to the DLL versions (mostly). There is a compile option to not add these directives, which is usually a good idea when building a static library. The «Ignore all default libraries» linker option tells the linker to ignore any directives present in the objects.

Alexander W. wrote:

.. I haven’t carried out all your suggestions from above yet. I started switching the property «Ignore all default libraries» to Yes and tried to compile, and then it works ..

@Alexander W.,

I’m curious about this thread of yours and where the discussion is going.  I ask because I dabble with mixed language projects involving Fortran every now and then and the only time I have encountered the error you indicated in the original post (error LNK2005: _powf already defined in lib..) was when the program main was not Fortran or when C++ DLL was involved and when Intel Fortran version used to compile the code was inconsistent with IFORT_COMPILER[vv] macro used in Visual Studio solution property settings for header files and library directories e.g., using Intel Fortran compiler 18.0 to compile Fortran source and linking to C++ main but with a setting that employs IFORT_COMPILER17; now if the macro is reset to IFORT_COMPILER18, then the link error disappears:

  1. So if your main program is not in Fortran or C++ DLL is involved, can you confirm you are following the instructions on this page?  https://software.intel.com/en-us/articles/configuring-visual-studio-for-mixed-language-applications
  2. Or if your situation is that of a Fortran program calling C++ functions via a link to a static C++ library, can you please look at Quote #6 in this thread https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/699941, ;try out the simple complete solution provided in the Example.zip attachment, and report here if it works?

Thanks,

@FortranFan:

Thanks for your suggestions. I tried out the possible solutions, but nothing worked. Again for info: I can built a Release-DLL successfully, and in a non-DLL solution I can debug into the C++ project as well, so in principle the inclusion of a C++ project to Fortran works. The only thing that does not work is a debug-DLL.

What I’ve tried now (according to Steves advices):

I have carried out a dumpbin directive for each of the projects (the ones that build a static library) that are linked in. Then I set the option «Ignore all default libraries» and linked in only the default-libs that are really needed. The same I did for the Main-Project (DLL),  but this did not work! I got 500+ errors «error LNK2019: unresolved external symbol […]».

When I switch the options back to «Ignore all refault libraries» to «No», I still get the message «error LNK2005: _powf already defined in libmmt.lib(powf_iface_c99.obj)».

It’s getting really frustrating, but maybe you still have an idea.

To quote #6: «Then you’ll have to name all of the required libraries (such as libifcoremd) in the Linker > Additional Dependencies property. This will take some effort to sort out.»

«The same I did for the Main-Project (DLL),  but this did not work! I got 500+ errors «error LNK2019: unresolved external symbol […]».«

This can surely only because there are required libs that you have not included. 

Alexander W. wrote:

..  When I switch the options back to «Ignore all refault libraries» to «No», I still get the message «error LNK2005: _powf already defined in libmmt.lib(powf_iface_c99.obj)».

It’s getting really frustrating, but maybe you still have an idea.

@Alexander W.,

If you really, really want to resolve your linker error LNK2005 and overcome the ensuing frustration with it, then I’ll suggest you provide the details.  I think you have posted verbiage but that’s not sufficiently actionable for any readers to give you concrete solutions.

Consider this thread again and specifically Quote #6 in it with a ZIP file attachment: you should be able to put together a small Visual Studio solution example with your Fortran (DLL?) and C++ (static library) projects where all the selections (compiler options, linker options, library specifications, etc.) match your actual solution and project files.  Share such a ZIP attachment containing your solution, project and source files which reproduce the linker error.  Note you can have some simple code, say calculate 3.14 to the power of n (pick some value for n) in C++ and assign the result to some variable in Fortran.  This will help review what is going on and point toward a resolution.

I tried to do what you advised, and created a new Fortran solution with a linked C++ project, using the same settings and properties as the solution that I’m trying to fix. I couldn’t reproduce the error, so I compared every single property and finally got it running:

In my solution I have 7 projects added, 6 Fortran, 1 C++. Now all of the them have Libraries/Run-Time-Library: «Multithreaded DLL» (thus no static linking). Non of the projects ignores all default libraries (so no library is explicitly added or ignored).

Maybe some day this may help somebody who has the same problem.

Alexander W. wrote:

.. Now all of the them have Libraries/Run-Time-Library: «Multithreaded DLL» (thus no static linking). Non of the projects ignores all default libraries (so no library is explicitly added or ignored).

Maybe some day this may help somebody who has the same problem.

«Maybe some day .. somebody who has the same problem.» will do better to first refer to Intel documentation, an easy click away: https://software.intel.com/en-us/fortran-compiler-19.0-developer-guide-and-reference-building-intel-…

Intel® Fortran Compiler .. Developer Guide and Reference wrote:

.. You must take care to choose the same type of run-time libraries in both your Fortran and C project. For example, if you select Multithreaded DLL in your Fortran project, you must select Multithreaded DLL in your C project. Otherwise, when your build your mixed Fortran/C application, you will receive errors from the Linker regarding undefined and/or duplicate symbols. ..


  • All forum topics


  • Previous topic

  • Next topic

It’s difficult to be helpful with so little detail to go on but here are some things to think about.

Platform Dependent Code

It’s not impossible that your code is at fault — for example you could perhaps have #ifdef code that depends on the platform being built. That could mean your Win32 and Win64 builds are compiling different code. But the fact your code builds successfully in Visual Studio 2010 suggests this is unlikely.

A variation of this might be a standard header which has changed between Visual Studio 2010 and Visual Studio 2013 in some platform dependent way. But again this doesn’t seen likely — things aren’t supposed to break just because you include a header.

Platform Dependent Properties

A common source of build errors in multi-platform solutions is a difference in project settings for the two platforms. Of course some properties are supposed to be different between Win32 and Win64 but others should be identical, or should be the «same» in the sense that they use the 32 and 64 bit versions of the same setting.

It’s worth looking through all of your Project settings for unintended differences between the two platforms. Since you are getting a linker error it might be especially worth examining the Linker’s «Additional Library Directories» and «Additional Dependencies» settings. Remember that x64 code must link to x64 versions of files — either by using a different file name or by linking to a file in an x64 specific directory.

One trick to looking for property variations is to open Project Properties and set «Platform» to «All platforms». Then look for individual properties with a value of «<different options>». I think this works in Visual Studio 2013, it certainly works in Visual Studio 2015 (sorry, I don’t have VS 2013 installed anywhere convenient).

Linker Diagnostics

Another potential approach is to turn on the Linker /verbose option and compare the output of the Win32 and Win64 builds. There will be a lot of output but you may be able to use «find» or a diff tool to look for differences in where/how __CIpow and _pow are linked that may give you a clue. The bad news is it probably won’t point directly at your problem’s cause. You’ll have to work backwards from what the Linker is actually doing, combined with some detective work and experimentation to figure out what’s actually happening.

Breaking Changes

Another possibility since you are upgrading from Visual Studio 2010 to Visual Studio 2013 is Breaking Changes. You’ll have to work through the list of Breaking Changes introduced in Visual Studio 2012 and the list of Breaking Changes introduced in Visual Studio 2013 looking for something that might produce the symptoms you are getting.

Accidents

If you haven’t already done so, you should confirm that the Visual Studio 2010 version of your solution builds successfully for both Wn32 and Win64.

Assuming it does, use your favourite diff tool to compare the .sln and .vcxproj files from the 2010 and 2013 versions. Look for changes that don’t seem to make sense in the current context. It’s always possible that something got changed inadvertently.

Finally, if you have a system with both Visual Studio 2010 and Visual Studio 2013 installed, you could use the Platform Toolset property to use Visual Studio 2013 to build your project with the Visual Studio 2010 toolset. If you find that the solution compiles and links successfully using with the 2010 (v100) toolset but fails with the 2013 (v120) toolset that may tell you something.

Вот, что осталось после добавления всех подряд файлов в проект (не знаю насколько верное решение если там несколько программ разных).

Кликните здесь для просмотра всего текста

Ошибка 17 Compilation Aborted (code 1) L:TMPtestPOGRTERMGRTERM.FOR 1
Предупреждение 3 warning #5105: LARGE directive statement not supported L:TMPtestPOGRTERMGRTERM.FOR 2
Предупреждение 1 warning #5105: DO66 directive statement not supported L:TMPtestPOProjectCEDSVVEDS.FOR 1
Предупреждение 2 warning #5105: DO66 directive statement not supported L:TMPtestPOGRTERMGRTERM.FOR 1
Ошибка 11 error #6633: The type of the actual argument differs from the type of the dummy argument. [TNR] L:TMPtestPOGRTERMGRTERM.FOR 346
Ошибка 10 error #6633: The type of the actual argument differs from the type of the dummy argument. [TNAC] L:TMPtestPOGRTERMGRTERM.FOR 334
Ошибка 12 error #6633: The type of the actual argument differs from the type of the dummy argument. [TKON] L:TMPtestPOGRTERMGRTERM.FOR 358
Ошибка 13 error #6633: The type of the actual argument differs from the type of the dummy argument. [FN] L:TMPtestPOGRTERMGRTERM.FOR 377
Ошибка 14 error #6633: The type of the actual argument differs from the type of the dummy argument. [0.] L:TMPtestPOGRTERMGRTERM.FOR 416
Ошибка 15 error #6633: The type of the actual argument differs from the type of the dummy argument. [0.] L:TMPtestPOGRTERMGRTERM.FOR 497
Ошибка 9 error #6601: In a CASE statement, the case-value must be a constant expression. [$OCGA] L:TMPtestPOGRTERMGRTERM.FOR 45
Ошибка 6 error #6601: In a CASE statement, the case-value must be a constant expression. [$MCGA] L:TMPtestPOGRTERMGRTERM.FOR 45
Ошибка 8 error #6601: In a CASE statement, the case-value must be a constant expression. [$HGC] L:TMPtestPOGRTERMGRTERM.FOR 45
Ошибка 7 error #6601: In a CASE statement, the case-value must be a constant expression. [$CGA] L:TMPtestPOGRTERMGRTERM.FOR 45
Ошибка 5 error #6424: This name has already been used as an external subroutine name. [NUL] L:TMPtestPOGRTERMGRTERM.FOR 21
Ошибка 4 error #6401: The attributes of this name conflict with those made accessible by a USE statement. [NUL] L:TMPtestPOGRTERMGRTERM.FOR 21
Ошибка 16 error #6285: There is no matching specific subroutine for this generic subroutine call. [SETTEXTPOSITION] L:TMPtestPOGRTERMGRTERM.FOR 557

There is no matching specific subroutine for this generic subroutine call. [SETTEXTPOSITION] С этим видимо тоже скорее всего придется разбираться отдельно. Это часть QuickWin если я правильно помню и скорее всего нужно использовать для графияеской библиотеки что-то из разряда IFQWIN

Добавлено через 6 минут
Собрал проект QuickWin Aзplication. Стало вот так, и это видимо правильное направление

Кликните здесь для просмотра всего текста

Ошибка 19 Compilation Aborted (code 1) L:TMPtestPOGROBRFKART.FOR 1
Предупреждение 14 warning #6075: The data type of the actual argument does not match the definition. [YNR] L:TMPtestPOGROBRFKART.FOR 109
Предупреждение 6 warning #6075: The data type of the actual argument does not match the definition. [YN] L:TMPtestPOGROBRFOKNO.FOR 7
Предупреждение 16 warning #6075: The data type of the actual argument does not match the definition. [YKR] L:TMPtestPOGROBRFKART.FOR 109
Предупреждение 8 warning #6075: The data type of the actual argument does not match the definition. [YK] L:TMPtestPOGROBRFOKNO.FOR 7
Предупреждение 13 warning #6075: The data type of the actual argument does not match the definition. [XNR] L:TMPtestPOGROBRFKART.FOR 109
Предупреждение 5 warning #6075: The data type of the actual argument does not match the definition. [XN] L:TMPtestPOGROBRFOKNO.FOR 7
Предупреждение 15 warning #6075: The data type of the actual argument does not match the definition. [XKR] L:TMPtestPOGROBRFKART.FOR 109
Предупреждение 7 warning #6075: The data type of the actual argument does not match the definition. [XK] L:TMPtestPOGROBRFOKNO.FOR 7
Предупреждение 17 warning #6075: The data type of the actual argument does not match the definition. L:TMPtestPOGROBRFKART.FOR 173
Предупреждение 18 warning #6075: The data type of the actual argument does not match the definition. L:TMPtestPOGROBRFKART.FOR 173
Предупреждение 10 warning #5105: LARGE directive statement not supported L:TMPtestPOGROBRFKART.FOR 3
Предупреждение 1 warning #5105: DO66 directive statement not supported L:TMPtestPOGROBRFGRFMF.FOR 1
Предупреждение 2 warning #5105: DO66 directive statement not supported L:TMPtestPOGRTERMGOCDT.FOR 1
Предупреждение 3 warning #5105: DO66 directive statement not supported L:TMPtestPOCTMCTM.FOR 1
Предупреждение 4 warning #5105: DO66 directive statement not supported L:TMPtestPOGRTERMYESNOU.FOR 1
Предупреждение 9 warning #5105: DO66 directive statement not supported L:TMPtestPOGROBRFKART.FOR 2
Ошибка 11 error #6601: In a CASE statement, the case-value must be a constant expression. [$MCGA] L:TMPtestPOGROBRFKART.FOR 57
Ошибка 12 error #6601: In a CASE statement, the case-value must be a constant expression. [$CGA] L:TMPtestPOGROBRFKART.FOR 57

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 extern in 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 it extern, 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 inline keyword 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 const variable is defined twice, and has a different value in each definition. To fix this issue, define the constant only once, or use namespaces or enum class definitions 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.

Я пытаюсь обновить работающее решение C ++ и Fortran с Visual Studio 2010 до 2013. При обновлении платформа Win32 собирается регулярно, но Win64 выдает следующие ошибки:

error LNK2005: __CIpow already defined in libmmt.lib(pow_stub.obj)
error LNK2005: _pow already defined in libmmt.lib(pow_stub.obj)
fatal error LNK1169: one or more multiply defined symbols found

Я понятия не имею, почему он основан только на Win32 или что я могу сделать, чтобы это исправить. Буду признателен за любую оказанную помощь.

0

Решение

Трудно быть полезным с таким небольшим количеством деталей, но вот некоторые вещи, о которых нужно подумать.

Зависимый от платформы код

Не исключено, что ваш код виноват — например, вы могли бы иметь #ifdef код, который зависит от создаваемой платформы. Это может означать, что ваши сборки Win32 и Win64 компилируют разный код. Но тот факт, что ваш код успешно собирается в Visual Studio 2010, говорит о том, что это маловероятно.

Разновидностью этого может быть стандартный заголовок, который изменился между Visual Studio 2010 и Visual Studio 2013 в зависимости от платформы. Но опять же это маловероятно — вещи не должны ломаться только потому, что вы включаете заголовок.

Зависимые от платформы свойства

Распространенным источником ошибок сборки в мультиплатформенных решениях является разница в настройках проекта для двух платформ. Конечно, некоторые свойства предполагаемый отличаться между Win32 и Win64, но другие должны быть идентичными или должны быть «одинаковыми» в том смысле, что они используют 32- и 64-разрядные версии одного и того же параметра.

Стоит просмотреть все настройки вашего проекта на предмет непреднамеренных различий между двумя платформами. Так как вы получаете ошибку компоновщика, может быть особенно целесообразно проверить настройки компоновщика «Дополнительные каталоги библиотеки» и «Дополнительные зависимости». Помните, что код x64 должен ссылаться на версии файлов x64 — либо с использованием другого имени файла, либо путем ссылки на файл в каталоге, специфичном для x64.

Один из способов поиска вариантов свойств — открыть Свойства проекта и установить для «Платформы» значение «Все платформы». Затем найдите отдельные свойства со значением «<разные варианты>». Я думаю это работает в Visual Studio 2013, конечно же, работает в Visual Studio 2015 (извините, VS 2013 не установлен где-либо удобно).

Линкер Диагностика

Другой потенциальный подход состоит в том, чтобы включить Линкер / подробный вариант и сравните выходные данные сборок Win32 и Win64. Там будет много вывода, но вы можете использовать «найти» или инструмент сравнения, чтобы найти различия в том, где и как __CIpow а также _pow связаны, которые могут дать вам подсказку. Плохая новость в том, что она, вероятно, не будет указывать непосредственно на причину вашей проблемы. Вам придется вернуться назад к тому, что на самом деле делает Линкер, в сочетании с какой-то детективной работой и экспериментами, чтобы выяснить, что на самом деле происходит.

Ломать перемены

Еще одна возможность, поскольку вы обновляете Visual Studio 2010 до Visual Studio 2013, — это критические изменения. Вам придется работать через список Внушительные изменения, представленные в Visual Studio 2012 и список Разрушительные изменения, представленные в Visual Studio 2013 ищет что-то, что может вызвать симптомы, которые вы получаете.

Несчастные случаи

Если вы этого еще не сделали, убедитесь, что версия вашего решения для Visual Studio 2010 успешно собирается как для Wn32, так и для Win64.

Предполагая, что это так, используйте ваш любимый инструмент сравнения для сравнения файлов .sln и .vcxproj из версий 2010 и 2013. Ищите изменения, которые, кажется, не имеют смысла в текущем контексте. Всегда возможно, что что-то изменилось непреднамеренно.

Наконец, если у вас есть система с установленными Visual Studio 2010 и Visual Studio 2013, вы можете использовать Набор инструментов платформы свойство использовать Visual Studio 2013 для создания проекта с помощью набора инструментов Visual Studio 2010. Если вы обнаружите, что решение успешно компилируется и связывается с использованием набора инструментов 2010 (v100), но не работает с набором инструментов 2013 (v120), это может вам кое-что сказать.

0

Другие решения

Других решений пока нет …

Hi,

I am porting the application with old fortran compiler and old visual studio(VC5) to new fortran compiler 11 and visual studio  2005. Application contains both ‘C’ and fortran code. I am compiling the fortran code and creating library called server_lib.lib(library is createing with some warnings) and linking to the ‘C’ code. while linking application is giving some below linking errors.

2>Linking…
2>server_lib.lib(Preparx.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Query.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Utm.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Runvhf.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(PFLTPV.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Qdesic.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Headach.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Plotky.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Terrain.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Morpho.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Diflos.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Micro.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(OpenGL_F.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Violet.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Fieldp.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(Step.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>server_lib.lib(White.obj) : error LNK2005: _SERVERSTUFF already defined in server_lib.lib(Athena7.obj)
2>.Debug/Server.exe : fatal error LNK1169: one or more multiply defined symbols found

above «serverstuff» is defined in server.for file and this server.for is included in all above files. Please find the below code block from server.for file.

INTEGER iErrPipe !error code for pipe i/o
INTEGER clientIndex !index into client list
CHARACTER*136 Buffer(17) !buffer for pipe i/o
CHARACTER dBuffer(2313) !buffer for pipe i/o
EQUIVALENCE(dBuffer,Buffer)
COMMON/serverstuff/clientIndex,dBuffer

DATA dBuffer(2313)/0/

Why the above code is giving redecleration error? How it worked with previous fortran compiler? When I am commenting the «COMMON/serverstuff/clientIndex,dBuffer» line then it’s linking perfectly, but the application is crashed..

Please give me any idea as I don’t know about fortran language

Solving pesky LNK2005 errors…

For those who read this blog and aren’t technically inclined or simply don’t use Microsoft Visual Studio (e.g. you use a different compiler suite), this entry isn’t for you.

One of most annoying things to run into in Visual C++ are linker errors. They are obtuse, poorly documented, and double-clicking them doesn’t take you to the source code (or the part of the object file) where the problem is occurring. One of the most confounding error messages is the LNK2005 error message. Usually something like this shows up:

nafxcwd.lib(afxmem.obj) : error LNK2005 …something about operator new/delete goes here…

If you search Google, a Microsoft Knowledgebase (KB) article pops up (KB148652):

http://support.microsoft.com/kb/148652

A lot of people run into LNK2005 errors, find the above article, try out what it says, and discover the «solution» makes the problem worse, not better. That is the only KB article I’ve ever seen that provides an incorrect solution for a problem…usually Microsoft is pretty good about giving right answers.

There are four causes of LNK2005 errors that I’ve run into and actually fixed:

1) A bad build. For some reason or other VS just occasionally barfs. The solution in this case is to close down VS, wipe all the temporary files (e.g. .obj, .dll, .exe, autogenerated MIDL .c files, etc.), load up VS, and do a Build->Clean Solution, Build->Rebuild Solution. Depending on the size of your solution, this can take a while — go grab a coffee.

2) If it still fails with LNK2005 errors, then something is mismatched. Right-click on each of the projects and select «Properties…». Then make sure the «‘C++’->Code Generation->Runtime Library» all say the exact same thing. If you attempt to use different runtime libraries, it may or may not link properly. The reason it will not link is if you allocate memory in one project and then pass it to another project and free it there (sort of like DLLs but weirder). If you are like me and have projects shared between solutions, you will want multiple project compilation types so that you don’t have problems with linker errors (I have 6 of 8 possible for my base library — the base library is multi-threaded — I say 8 possible because you have /MD[d] with MFC, which is different than /MD[d]). Once you have types matching (don’t forget to match the «use MFC» option if you use MFC!), make sure both debug and release mode are configured correctly with the configuration manager (Right-click on «Solution ‘solutionname’ (x projects)» and select «Configuration manager…»). Also, make sure the dependencies and build order are correct (same right-click menu but «Project dependencies…» and «Project build order…» instead).

3) If you’ve done all that and still get LNK2005 errors, then you’ve hit a scenario I like to call the «duh» scenario. An incorrect entry point for the subsystem selected will raise a LNK2005 error message. So, if you defined main() and don’t use /SUBSYSTEM:CONSOLE, you’ll get a LNK2005 error. Or if you defined WinMain() and don’t use /SUBSYSTEM:WINDOWS, you’ll get a LNK2005 error. Again, this doesn’t always happen, but when it does it is weird (usually complains about new/delete duplications across object files instead of main()/WinMain()). To change the subsystem, right-click on the startup project and select «Properties…». Then go to Linker->System->SubSystem. Change accordingly to the entry point used.

4) If, even after all that you still get LNK2005 errors, then it is time to scratch your head and think, «Gee, did I or any third party put in any include files that force .lib files to be included in the linking stage?» Start scouring that source code for any #pragma comment(lib, …) statements. This happens particularly with MFC libraries since there is code floating around out there that forces the MFC libraries to be linked in at link time first and then forces the other libraries to be excluded — including such code with a non-MFC project causes all sorts of headaches since the other libraries are loaded first and thus can’t be excluded by the #pragma and then the MFC libraries attempt to get linked in and fail. But it can happen in other cases as well — even indirectly via a third-party library.

I’ve never experienced this, but according to what people say on the Internet, when they run into LNK2005 errors, they completely rebuild all of the projects in their solution from scratch (i.e. brand new .sln and .vcproj files). It would take me several days to do that, so that is not an option for me. But apparently it can work. My guess: They implicitly did #1 and #2 by taking that approach — only it took way longer than necessary.

A lot of people suggest turning on /VERBOSE in the linker options. In my experience, that rarely helps to do anything but create more confusion. The option exists, so it is probably useful in some cases.

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

Понравилась статья? Поделить с друзьями:
  • Error lnk2005 already defined in libcmtd lib
  • Error lnk2001 неразрешенный внешний символ main
  • Error lnk2001 неразрешенный внешний символ cxxframehandler3
  • Error lnk2001 unresolved external symbol winmain 16
  • Error lnk2001 unresolved external symbol purecall