Msbuild exit on error

Error — задача Останавливает сборку и регистрирует ошибку в журнале событий на основании вычисленного условного оператора. Параметры В следующей таблице приводятся параметры задачи Error . Параметр Описание Code Необязательный параметр String . Код ошибки для связи с ошибкой. File Необязательный параметр String . Имя файла, содержащего ошибку. Если имя файла не указано, используется файл, […]

Содержание

  1. Error — задача
  2. Параметры
  3. Remarks
  4. Пример
  5. Error task
  6. Parameters
  7. Remarks
  8. Example
  9. Диагностика сбоев задач MSBuild
  10. Определение задачи, завершиющейся сбоем
  11. Дополнительные сведения о сбоях
  12. Практическое руководство. Игнорирование ошибок в задачах
  13. Использование атрибута ContinueOnError
  14. Игнорирование ошибки в задаче
  15. Пример
  16. Diagnose MSBuild task failures
  17. Identify the failing task
  18. Find more failure information

Error — задача

Останавливает сборку и регистрирует ошибку в журнале событий на основании вычисленного условного оператора.

Параметры

В следующей таблице приводятся параметры задачи Error .

Параметр Описание
Code Необязательный параметр String .

Код ошибки для связи с ошибкой.

File Необязательный параметр String .

Имя файла, содержащего ошибку. Если имя файла не указано, используется файл, содержащий задачу Error.

HelpKeyword Необязательный параметр String .

Ключевое слово справки для связи с ошибкой. Только для внутреннего использования.

HelpLink Необязательный параметр String .

Ссылка на дополнительные сведения об ошибке.

Text Необязательный параметр String .

Текст ошибки, регистрируемый в журнале MSBuild, если результат вычисления параметра Condition оказывается равным true .

Задача Error позволяет передавать текст ошибок в средства ведения журнала и останавливать выполнение сборки в проектах MSBuild.

Если результат вычисления параметра Condition оказывается равным true , сборка останавливается, а ошибка регистрируется в журнале. Если параметр Condition не существует, ошибка регистрируется в журнале, а выполнение сборки останавливается. Дополнительные сведения о ведении журнала см. в разделе Получение журналов сборки.

Помимо перечисленных выше параметров, эта задача наследует параметры от класса TaskExtension, который, в свою очередь, наследует от класса Task. Список этих дополнительных параметров и их описания см. в статье Базовый класс TaskExtension.

HelpKeyword используется Visual Studio для поддержки функции контекстной справки (F1). С помощью HelpLink можно связать страницу справки в Интернете с сообщением об ошибке.

Пример

В следующем примере кода проверяется, что установлены все обязательные свойства. Если это не так, проект инициирует событие ошибки и регистрирует в журнале значение параметра Text задачи Error .

Источник

Error task

Stops a build and logs an error based on an evaluated conditional statement.

Parameters

The following table describes the parameters of the Error task.

Parameter Description
Code Optional String parameter.

The error code to associate with the error.

File Optional String parameter.

The name of the file that contains the error. If no file name is provided, the file containing the Error task will be used.

HelpKeyword Optional String parameter.

The help keyword to associate with the error. For internal use only.

HelpLink Optional String parameter.

A link to more information about the error.

Text Optional String parameter.

The error text that MSBuild logs if the Condition parameter evaluates to true .

The Error task allows MSBuild projects to issue error text to loggers and stop build execution.

If the Condition parameter evaluates to true , the build is stopped, and an error is logged. If a Condition parameter does not exist, the error is logged and build execution stops. For more information on logging, see Obtaining build logs.

In addition to the parameters listed above, this task inherits parameters from the TaskExtension class, which itself inherits from the Task class. For a list of these additional parameters and their descriptions, see TaskExtension base class.

HelpKeyword is used by Visual Studio to support the contextual help feature (F1). You can use HelpLink to associate an online help page with an error message.

Example

The following code example verifies that all required properties are set. If they are not set, the project raises an error event, and logs the value of the Text parameter of the Error task.

Источник

Диагностика сбоев задач MSBuild

MSB6006 вызывается, когда класс, производный от ToolTask, выполняет процесс средства, возвращающий ненулевой код выхода, если задача не зарегистрировала более конкретную ошибку.

Определение задачи, завершиющейся сбоем

При возникновении ошибки задачи в первую очередь нужно определить задачу, которая завершается сбоем.

В тексте ошибки указывается имя инструмента (понятное имя, предоставленное реализацией задачи ToolName, или имя исполняемого файла) и числовой код выхода. Например, в error MSB6006: «custom tool» exited with code 1. имени средства используется custom tool код 1 выхода.

Чтобы найти неудачную задачу MSBuild, выполните следующие действия.

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

Этот результат указывает, что ошибка произошла в задаче, определенной в строке 19 файла S:MSB6006_demoMSB6006_demo.csproj , в целевом объекте с именем InvokeToolTask в проекте S:MSB6006_demoMSB6006_demo.csproj .

В пользовательском интерфейсе Visual Studio: те же сведения доступны в списке ошибок Visual Studio в столбцах Project File и Line .

Дополнительные сведения о сбоях

Эта ошибка возникает, если задача не регистрирует определенную ошибку. Сбой регистрации ошибки часто возникает, так как в задаче не предусмотрено распознавание формата ошибки, генерируемой средством, которое она вызывает.

Правильно работающие средства обычно выдают некоторые контекстные сведения или сведения об ошибках в стандартный вывод или поток ошибок, а задачи записывают эти сведения по умолчанию. Просмотрите записи журнала до возникновения ошибки, чтобы получить дополнительные сведения. Для сохранения этих сведений может потребоваться перезапустить сборку с более высоким уровнем ведения журнала. Надеемся, что дополнительный контекст или ошибки, обнаруженные в журнале, позволят выявить основную причину проблемы. В противном случае может потребоваться сузить потенциальные причины, проверив свойства и элементы, которые являются входными данными для неудающейся задачи.

MSBuild распознает определенный формат выходных данных диагностики. Сведения об этом формате задокументированы в разделе Формат MSBuild и Visual Studio для диагностических сообщений.

Источник

Практическое руководство. Игнорирование ошибок в задачах

Иногда требуется, чтобы сборка была отказоустойчивой при выполнении определенных задач. В случае появления ошибки в таких некритических задачах сборку можно продолжить, поскольку это не помешает получить требуемый результат. Например, если в проекте используется задача SendMail для отправки сообщения электронной почты после сборки каждого компонента, вы можете пожелать продолжить сборку до полного завершения даже в том случае, если почтовые серверы оказываются недоступными и не удается отправить сообщения о состоянии. Или, например, если промежуточные файлы обычно удаляются во время сборки, вы можете пожелать продолжить выполнение сборки до полного завершения даже в том случае, если эти файлы не удается удалить.

Использование атрибута ContinueOnError

Атрибут ContinueOnError элемента Task определяет, следует ли остановить или продолжить сборку в случае, если в задаче произошла ошибка. Этот атрибут также контролирует, обрабатываются ли ошибки в виде ошибки или предупреждения, когда сборка продолжается.

Атрибут ContinueOnError может содержать одно из следующих значений:

WarnAndContinue или true. При сбое задачи последующие задачи в элементе Target и сборке продолжают выполняться, а все ошибки из задачи рассматриваются как предупреждения.

ErrorAndContinue. При сбое задачи последующие задачи в элементе Target и сборке продолжают выполняться, а все ошибки из задачи рассматриваются как ошибки.

ErrorAndStop или false (по умолчанию). При сбое задачи остальные задачи в элементе Target и сборке не выполняются, и считается, что возник сбой всего элемента Target и всей сборки.

Версии платформы .NET Framework, предшествовавшие 4.5, поддерживали только значения true и false .

Значением свойства ContinueOnError по умолчанию является ErrorAndStop . Если задать для атрибута значение ErrorAndStop , можно сделать такое поведение явным для всех объектов, считывающих файл проекта.

Игнорирование ошибки в задаче

Используйте атрибут ContinueOnError задачи. Пример:

Пример

В следующем примере кода показано, что целевой объект Build по-прежнему выполняется, а сборка считается успешной, даже если задача Delete завершается с ошибкой.

Источник

Diagnose MSBuild task failures

MSB6006 is emitted when a ToolTask–derived class runs a tool process that returns a nonzero exit code if the task did not log a more specific error.

Identify the failing task

When you encounter a task error, the first step is to identify the task that is failing.

The text of the error specifies the tool name (either a friendly name provided by the task’s implementation of ToolName or the name of the executable) and the numeric exit code. For example, in error MSB6006: «custom tool» exited with code 1. the tool name is custom tool and the exit code is 1 .

To find the failed MSBuild task:

In the command-line builds: If the build was configured to include a summary (the default), the summary will look like this:

This result indicates that the error occurred in a task defined on line 19 of the file S:MSB6006_demoMSB6006_demo.csproj , in a target named InvokeToolTask , in the project S:MSB6006_demoMSB6006_demo.csproj .

In the Visual Studio UI: The same information is available in the Visual Studio error list in the columns Project , File , and Line .

Find more failure information

This error is emitted when the task did not log a specific error. The failure to log an error is often because the task is not configured to understand the error format emitted by the tool it calls.

Well-behaved tools generally emit some contextual or error information to their standard output or error stream, and tasks capture and log this information by default. Look in the log entries before the error occurred for additional information. Rerunning the build with a higher log level may be required to preserve this information. Hopefully, the additional context or errors identified in logging reveal the root cause of the problem. If not, you may have to narrow down the potential causes by examining the properties and items that are inputs to the failing task.

MSBuild recognizes a specific diagnostic output format. The details of this format are documented at MSBuild and Visual Studio format for diagnostic messages.

Источник

I tested this (building MSBuild.sln). Here’s part of my (diagnostic) log:

  MSBuild -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMSBuildDebugnetcoreapp2.1MSBuild.dll
  MSBuild.Engine.Corext -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMSBuild.Engine.CorextDebugnet472
  MSBuild.Engine.Corext.dll
  DevDivPackage -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinDevDivPackageDebugnet472DevDivPackage.dl
  l
  Microsoft.Build.CommandLine.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Com
  mandLine.UnitTestsDebugnet472Microsoft.Build.CommandLine.UnitTests.dll
  Microsoft.Build.Tasks.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Tasks.Uni
  tTestsDebugnet472Microsoft.Build.Tasks.UnitTests.dll
  MSBuild.Bootstrap -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMSBuild.BootstrapDebugnetcoreapp2.1M
  SBuild.Bootstrap.dll
  Microsoft.Build.Engine.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Engine.U
  nitTestsDebugnet472Microsoft.Build.Engine.UnitTests.dll
  Microsoft.Build.Utilities.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Utili
  ties.UnitTestsDebugnetcoreapp2.1Microsoft.Build.Utilities.UnitTests.dll
C:UsersforgindDocumentsGitHubmsbuildsrcBuild.OM.UnitTestsLazyFormattedEventArgs_Tests.cs(31,13): error CS1002:
 ; expected [C:UsersforgindDocumentsGitHubmsbuildsrcBuild.OM.UnitTestsMicrosoft.Build.Engine.OM.UnitTests.cspr
oj]
C:UsersforgindDocumentsGitHubmsbuildsrcBuild.OM.UnitTestsLazyFormattedEventArgs_Tests.cs(36,9): error CS0650:
Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fi
xed size buffer field, use the fixed keyword before the field type. [C:UsersforgindDocumentsGitHubmsbuildsrcBui
ld.OM.UnitTestsMicrosoft.Build.Engine.OM.UnitTests.csproj]
C:UsersforgindDocumentsGitHubmsbuildsrcBuild.OM.UnitTestsLazyFormattedEventArgs_Tests.cs(36,10): error CS0270:
 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) [C:Usersforgind
DocumentsGitHubmsbuildsrcBuild.OM.UnitTestsMicrosoft.Build.Engine.OM.UnitTests.csproj]
C:UsersforgindDocumentsGitHubmsbuildsrcBuild.OM.UnitTestsLazyFormattedEventArgs_Tests.cs(36,15): error CS1002:
 ; expected [C:UsersforgindDocumentsGitHubmsbuildsrcBuild.OM.UnitTestsMicrosoft.Build.Engine.OM.UnitTests.cspr
oj]
  Microsoft.Build.Engine.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Engine.U
  nitTestsDebugnetcoreapp2.1Microsoft.Build.Engine.UnitTests.dll
  MSBuild.VSSetup -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMSBuild.VSSetupDebugnet472MSBuild.VSSe
  tup.dll
  MSBuild.Bootstrap -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMSBuild.BootstrapDebugnet472MSBuild.
  Bootstrap.dll
  Microsoft.Build.Utilities.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Utili
  ties.UnitTestsDebugnet472Microsoft.Build.Utilities.UnitTests.dll
  Localization -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinLocalizationDebugnetcoreapp2.1Localizatio
  n.dll
  MSBuild -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMSBuildx64Debugnet472MSBuild.exe
  Microsoft.Build.CommandLine.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Com
  mandLine.UnitTestsDebugnetcoreapp2.1Microsoft.Build.CommandLine.UnitTests.dll
  Microsoft.Build.Tasks.UnitTests -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMicrosoft.Build.Tasks.Uni
  tTestsDebugnetcoreapp2.1Microsoft.Build.Tasks.UnitTests.dll
  MSBuildTaskHost -> C:UsersforgindDocumentsGitHubmsbuildartifactsbinMSBuildTaskHostx64Debugnet35MSBuildTa
  skHost.exe

As you can see, it fails to build Build.OM.UnitTests, but it keeps going afterwards. Closing as could-not-reproduce.

One of the most annoying and common problems (as a bit of Googling soon reveals) when compiling a big project with MSBuild (multi-process) is that even if compilation fails on one of the files (due to a syntax error or some other error condition), it will keep compiling the rest of the codebase. This is bad for two reasons:
  1)  You won’t be able to link the program in the end anyway. At least in my experience, even if you could link the program (and that’s not a given in every case), it doesn’t make much (if any) sense to have an unreproducable chimera of old + new code (though exactly which bits they are you probably won’t remember a little down the track)

  2)  You’ll probably have to recompile all the code again once you fix the error anyway. More often than not, I’ve mainly had these errors show up when changnig code in a popular header file that large swathes of the program used. So, if a compile error like this showed up, the computer would have already wasted a lot of time/energy compiling a lot of files (many of them unsuccessfully too), work that would have to be redone when you’ve fixed the error anyway.

After a few false starts, I ended up finding a neat (if somewhat evil) little hack to solve this problem once and for all.

My Solution
I found that simply calling Environment.Exit(-1) from within an error-event handler in a CustomLogger could be used to stop a build process dead in its tracks. Instantly.

The hack in action. 

Someone more knowledgeable about how the MSBuild system might be able to tell me that doing so has certain downsides over more «officially sanctioned» ways of solving the problem. That said, IMO this should in theory be similar to just force-closing the terminal window anyway, or madly Ctrl-C’ing it into submission. Except this is more efficient and automated :)

So, here’s a minimal example of how we could do this:

using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;



public class CustomLogger: Logger
{

    public override void Initialize(IEventSource eventSource)
    {

        eventSource.ErrorRaised   += new BuildErrorEventHandler(handleErrorRaised);
     }


     private void handleErrorRaised(object sender, BuildErrorEventArgs e)
     {
           /* Report the error */
           string line = String.Format(«ERROR: {0}:{1} — {3}  [{2}]»,
                                    e.File, e.LineNumber, e.Code, e.Message);
            Console.WriteLine(line);

                  
            /* Try to trigger a stop */
            Console.WriteLine(«nStopping build now!»);

            Environment.Exit(-1);
        }
    }

}

(Warning: Untested code — Extracted from my full logger, but with just the key bits picked out)

Other Approaches That Didn’t Work
* The «StopOnFirstFailure» option that’s apparently available DOES NOT work when doing multi-process builds. The documentation tells us that much. But, even if it does work, it’s hard to come across any info about how I’m supposed to pass/set that option when my build files were all generated by CMake

* Another option is to try commanding MSBuild via the programmatic api (i.e. Microsoft.Build.Execution -> BuildManager). In theory, that’s how the VS IDE implements its Build.Cancel() functionality.

(That said, on the few occasions where I have used the VS IDE, I found that it too didn’t have anything in place to exit the build on the first error encountered. Perhaps the folks in Redmond just don’t care (or didn’t think it was worth allocating the resources to solving this problem).)

Anyway, here’s what I tried with the MSBuild Execution API’s: In a CustomLogger, I added a handler for Build Errors (as above). But, instead of directly exiting, I tried to force a graceful shutdown by using the DefaultBuildManager singleton (which I assumed should be the same instance that’s running the logger, and hence the current build job). Looking through the docs, I saw a few promising API’s that looked like they could be used to stop things in their tracks — namely, ShutdownAllNodes(), Dismiss(), and CancelAllSubmissions().

Of these candidates, ShutdownAllNodes() looked to be the most promising; however, no matter what I tried, I couldn’t get it to work, as I kept getting errors about missing symbols  (Note: I was compiling the code using csc directly on the commandline, and was passing it Microsoft.Build.dll as one of the «references», in addition to the existing logging ones).

All the other options could be compiled-into-the-logger without problems, but only caused the build process to stall (i.e. after the commands were issued, the build engine would continue to spawn whatever events it had pending, and then all the activity would then suddenly die out but not quit, with 2 MSBuild processes still active).

RRS feed

  • Remove From My Forums
  • Question

  • Hi,

    I have a project made of many files and would like the build to stop when an error is detected.

    It currently compiles all the files with or whitout errors. How can I specify the build to stop on error detected?

    Thank You.

    Charles

All replies

  • Bump an anunswered febuary thread

  • You can add the «Compile» command to the toolbar. This gives you the ability to compile one source file at a time.

    Right-click on toolbar, Customize, Commands tab, Build category, drag the Compile icon to your toolbar.

    • Proposed as answer by

      Friday, June 13, 2008 4:45 PM

  • This doesn’t answer the question.  The requested feature is for the entire build to stop when the first error is detected.

    The requested feature would save the time of the developers and
    builders of the project.  For example, let’s say it takes 30 minutes to
    build a large project.  If an error occurs 2 minutes into the build
    (for example an automated integration build), then 28 minutes of human
    time is wasted before the build problem will be addressed.  Sometimes
    the offending code might be a checkin from a different developer.

    Once the problem is found, of course the «compile» command is
    invaluable.  But anyone asking how to stop the entire build after the
    first error probably already knows about the «compile» command.

    Thank you.

  • I agree this is a really annoying default and seems to come from the inherent use of MSBuild, and it is still there in VS2008! How disappointing. 

    I think the design of MSBuild is limiting us here. Then that is where the issue should be fixed then everything would work sensibly and save lots of time, even for a stand-alone developer. I remember in the pre-MSBuild days there was an option (I used C++ then) to stop on first error and I think it was default. What happened?

    Did anyone find a workaround for this? Perhaps a special MSBuild task that can stop it’s chilren from building when the first fails? Needs project dependencies to be considered too because there could be multiple threads building at the same time.

  • hi, when building your app and if you see a there is a shortcut to stop the build (CTR + the break key (on most keybords it is the same key as the PAUSE key))
    i Have added a extra button to my toolbar that has the same effect.

    The button can be found by right kliking on the toolbar->Costumize…-> in the TAB Commands select the categorie Build and there you find a button «cancel»

    dragg it to a toolbar to add it.

    now when building you can klick on it and the build will stop.

    Hope that helps,…

    GRZ A.

    • Proposed as answer by
      azertykk
      Wednesday, April 8, 2009 7:13 PM

  • Thanks for the suggestion. When I notice the build is running wild after the first error I hit CTRL+BREAK to stop the build and if I’m luckz and VS doesn’t hang itself it’ll stop.

    What I am after is feature request so I’ll drop that in MS Connect and hope it appears in VS 2010.

  • I remember in the pre-MSBuild days there was an option (I used C++ then) to stop on first error and I think it was default. What happened?

    If that option ever existed it was never the default and I doubt that the option did exist ever. I have used VC since version 1 and I used the predecessor, the Microsoft C compiler before it was renamed to Visual C++. I have never seen that option; I am not saying it did not exist but I doubt that it did.

    If I work on a project in which I expect many errors from many files, I will compile one at a time; that is, do just a compile, not a build. If I do a build and I get many errors from many files, then I do the same thing; I fix errors in one file at a time and compile one at a time and repeat as necessary. I know of no other way to deal with the situation in which there are many errors from many files.


    Sam Hobbs; see my SimpleSamples.Info

  • a modified code from http://www.ehow.com/how_5025041_automatically-visual-studio-build-error.html by eric m,
    press Alt-F11 -> MyMacros -> EnvironmentEvents -> paste it before «End Module»

    Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated
    If Not (pPane.Name = "Build") Then Exit Sub
    
    pPane.TextDocument.Selection.SelectAll()
    Dim Context As String = pPane.TextDocument.Selection.Text
    pPane.TextDocument.Selection.EndOfDocument()
    
    Dim found As Integer = Context.IndexOf(": error ")
    Dim foundFatal As Integer = Context.IndexOf(": fatal error")
    
    If found > 0 Or foundFatal > 0 Then
    DTE.ExecuteCommand("Build.Cancel")
    End If
    
    End Sub 
    • Proposed as answer by
      Code Chief
      Tuesday, July 14, 2009 11:02 AM

  • Simple Samples, thanks for the correction but that doesn’t help with the solution. I too have used a lot of different compilers over the years from different companies, for many different languages and complexity levels (assembler — C — C++ — C#). I may not remember all the settings exactly but I never encountered such an annoying behaviour as a «run-away build», to give it a name.

    Trying to select and individual files is cumbersome and is not feasible when making changes across multiple projects, e.g. refactoring, building or extending object models.

    CTRL+BREAK was known from the start but the responsiveness of the VS UI is terrible during a build of a real meaty solution.

    Sonicth found the solution. It’s the best because it occurs immediately, is persisted with the user in their macros directory, is fully automatic and should be a supported way to extend VS behaviour.

    I think that little nugget should go on a VS development best practice list.

  • Thanks sonicth for the solution, that’s a nice workaround.

    I used the original code from the link you provided (below plus a couple of comments). Was there a reason you had to extend it with text comparison rather than the Success flag? Initial tests show it works as-is with VS2008 SP1.

    ‘ Handles the BuildProjConfigDone event to stop building after first project build fails.

    Private Sub BuildEvents_OnBuildProjConfigDone(ByVal Project As String, ByVal ProjectConfig As String, ByVal Platform As String, ByVal SolutionConfig As String, ByVal Success As Boolean) Handles BuildEvents.OnBuildProjConfigDone

    ‘ Automatically stop building on first error

    If Success = False Then

    DTE.ExecuteCommand(«Build.Cancel»)

    End If

    End Sub

  • Simple Samples, thanks for the correction but that doesn’t help with the solution.

    It helps better than sending a person on a search for something that does not exist.


    Sam Hobbs; see my SimpleSamples.Info

  • The title of the thread and desired solution was «How to stop build on error detected with Visual Studio 2005«.

  • You can add the «Compile» command to the toolbar. This gives you the ability to compile one source file at a time.

    Right-click on toolbar, Customize, Commands tab, Build category, drag the Compile icon to your toolbar.

    though technically correct, i am quite sure most people have more than one source file in their rather large business solution.

    this is not a solution for say a project with 100’s or perhaps 1000’s of source files that can take hours to build.  no one will sit there manually clicking away.


    Micky D

  • this is not a solution for say a project with 100’s or perhaps 1000’s of source files that can take hours to build.  no one will sit there manually clicking away.

    The solution for a project with 100’s or perhaps 1000’s of source files is multiple projects.

    I have not worked with projects that big, but if I did, I think it would be especially important to compile one file at a time. Of course, if I could, I would make the project multiple projects. In the relatively small projects I have worked with, it was distracting and wasteful to compile all files when I got errors. It was easier for me to fix errors for just one file at a time. In a project with 100 source files, chances are, we just have to fix the errors in one file and then most errors for most files go away. So we don’t have to click and click and click 100 times.


    Sam Hobbs; see my SimpleSamples.Info

  • Correction: I have worked with huge projects, but not when the computer was as powerful as they are now. In the days in which the projects I worked with were huge, it would be considered foolish to compile every source file every time that fixes were applied to a file in an application; that is, the equivalent of an application. What’s the purpose of doing that, other than wasting processing time that others could use?

    Of course, PCs are different; one machine does not support all development for a large staff of developers. There was a time when one computer would support all development from 50 programmers. Developers now have no problem casually compiling 100 source files all at once.

    Yes, it is foolish to «manually» compile every file to build a large project. That is not the purpose of a compile button. I guess I should have said that at the beginning; I apologize for ranting if it was not relevant.


    Sam Hobbs; see my SimpleSamples.Info

  • this is not a solution for say a project with 100’s or perhaps 1000’s of source files that can take hours to build.  no one will sit there manually clicking away.

    The solution for a project with 100’s or perhaps 1000’s of source files is multiple projects.

    that only does not fix the issue but is also irrelevant . not to mention slightly insulting .


    Micky D

  • I remember in the pre-MSBuild days there was an option (I used C++ then) to stop on first error and I think it was default. What happened?

    you are absolutely right, i just did a test with VC 6.

    Solution contains 2 projects , each with a number of files. if a compile error occurs during compiling of the first project it does not compile the second — which is good.

    Unlike Visual Studio 2005, 2008 which continues to build each consecutive project which is just plain silly.


    Micky D

  • now when building you can klick on it and the build will stop.

    Hope that helps,…

    GRZ A.

    you cant be serious? and why is this marked as an answer?


    Micky D

  • I remember in the pre-MSBuild days there was an option (I used C++ then) to stop on first error and I think it was default. What happened?

    If that option ever existed it was never the default and I doubt that the option did exist ever. I have used VC since version 1 and I used the predecessor, the Microsoft C compiler before it was renamed to Visual C++. I have never seen that option; I am not saying it did not exist but I doubt that it did.

    If I work on a project in which I expect many errors from many files, I will compile one at a time; that is, do just a compile, not a build. If I do a build and I get many errors from many files, then I do the same thing; I fix errors in one file at a time and compile one at a time and repeat as necessary. I know of no other way to deal with the situation in which there are many errors from many files.


    Sam Hobbs; see my SimpleSamples.Info

    really? i just did a test with VC 6 and it is NOT the case and it is the default behavior .

    Solution contains 2 projects , each with a number of files. if a compile error occurs during compiling of the first project it does not compile the second — which is good.

    begin of rebuild all with error in  first project (result is EXPECTED) ——————————————

    Deleting intermediate files and output files for project ‘MyLib — Win32 Debug’.
    Deleting intermediate files and output files for project ‘Test — Win32 Debug’.
    ———————Configuration: MyLib — Win32 Debug———————
    Compiling…
    StdAfx.cpp
    Compiling…
    test1.cpp
    C:Program FilesMicrosoft Visual StudioMyProjectsTestMyLibtest1.cpp(7) : fatal error C1004: unexpected end of file found
    test2.cpp
    Generating Code…
    Error executing cl.exe.

    Test.exe — 1 error(s), 0 warning(s)

    ——————————————————————-
    begin of rebuild all after fixing error in first project (result is EXPECTED) —————————

    Deleting intermediate files and output files for project ‘MyLib — Win32 Debug’.
    Deleting intermediate files and output files for project ‘Test — Win32 Debug’.
    ———————Configuration: MyLib — Win32 Debug———————
    Compiling…
    StdAfx.cpp
    Compiling…
    test1.cpp
    test2.cpp
    Generating Code…
    Creating library…
    ———————Configuration: Test — Win32 Debug———————
    Compiling resources…
    Compiling…
    StdAfx.cpp
    Compiling…
    Test.cpp
    C:Program FilesMicrosoft Visual StudioMyProjectsTestTest.cpp(23) : error C2143: syntax error : missing ‘;’ before ‘const’
    C:Program FilesMicrosoft Visual StudioMyProjectsTestTest.cpp(23) : error C2501: ‘kpokpokpk’ : missing storage-class or type specifiers
    MainFrm.cpp
    TestDoc.cpp
    TestView.cpp
    Generating Code…
    Error executing cl.exe.

    Test.exe — 2 error(s), 0 warning(s)

    ————————————————————
    Now if i did this in vs2005 or 2008 it would build both projects regardless.  Unlike Visual Studio 2005, 2008 which continues to build each consecutive project which is just plain silly.

    I have been using Microsoft c/c++ since the V5 DOS version, though I cant claim for certainty what V5 did, I suspect this behavior was not native to VC6.

    like the other poster said, it wasn’t until .NET was introduced did c++ get upset.


    Micky D

  •  It was easier for me to fix errors for just one file at a time. In a project with 100 source files, chances are, we just have to fix the errors in one file and then most errors for most files go away. So we don’t have to click and click and click 100 times.


    Sam Hobbs; see my SimpleSamples.Info

    hmmm anyone with lots of experience in c++ knows that sometimes the result of 1000 errors is caused by merely 1 faultunfortunately of the 1000 errors the majority are irrelevant because they are all in other projects which depend on the former.

    if VS2005 and 2008 behaved as its predecessors once did we would not see this sort of pollution.


    Micky D

  • agreed.

    the ‘solutions’ to the issue in this thread are perhaps questionable and am unclear why there are marked as answer indicators

    the last MS c++ that did the job right that I know of is VC++ 6.


    Micky D

  • Quite right. It’s a ludicrous change in behaviour by Microsoft. Many of the «answers» miss the point completely. With a large project, I’m sure many people do the same thing as me: set it compiling and go and do something else in the meantime. No one sits
    there for half an hour watching VS output scroll by, surely? If you see that VS is still compiling, you assume there’s no error. There’s nothing more annoying than finding that a project at the bottom of the pile failed half an hour ago. And to discover that,
    you have to wade through reams of useless output. If project B depends on project A, and project A fails, why bother continuing with project B?

    Absolutely insane. 

Я написал командный файл, который при запуске создает решение Visual Studio. Решение состоит из нескольких проектов C #. Для этого я использую утилиту MSBuild. Как я могу остановить дальнейшую сборку, если в любом из проектов есть ошибки компиляции? Далее, как я могу получить сообщения об ошибках и отобразить их в командной строке?

2 ответы

При создании решения Visual Studio не поддерживается остановка при первом сбое.

Вы можете обойти это, выполнив следующие действия:

  1. Установите для переменной среды msbuildemitsolution значение 1 (set msbuildemitsolution=1);
  2. Вызов MSBuild для создания файла * .proj из целевого решения VS;
  3. В сгенерированном файле * .sln.proj измените RunEachTargetSeparately="true" в цели с именем Build to RunEachTargetSeparately="false";
  4. Вызовите MSBuild, чтобы создать обновленный файл * .sln.proj.

Этот ответ основан на Дэн Мозли отвечает на сообщение на форумах MSDN.

ответ дан 15 мар ’11, в 13:03

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

msbuild.exe /m /p:Configuration=Release /v:n theSolutionFile.sln >Build.log
if ERRORLEVEL 1 goto :showerror
find "0 Warn" Build.log >nul:
if ERRORLEVEL 1 goto :showerror

goto :EOF

:showerror
echo Build error occurred
exit %ERRORLEVEL%

ответ дан 15 мар ’11, в 14:03

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

msbuild
batch-file
command-prompt

or задайте свой вопрос.

Понравилась статья? Поделить с друзьями:
  • Msbuild error msb1008 можно указать только один проект
  • Msbuild error msb1008 only one project can be specified
  • Msbuild error msb1003
  • Msbuild error msb1001 unknown switch
  • Msb3644 как исправить