Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# - 바이너리 출력 디렉터리와 연관된 csproj 설정

C# Console 응용 프로그램을 기본 생성하면 다음과 같은 구성을 갖고,

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

빌드하면, "프로젝트" 파일이 있는 위치를 기준으로 출력 디렉터리가 구성돼 결과물이 아래와 같이 모입니다.

C:\temp\ConsoleApp1\ConsoleApp1\bin\Debug\net7.0\ConsoleApp1.dll

이 상태에서 "net7.0"은 csproj의 TargetFramework에 지정된,

<TargetFramework>net7.0</TargetFramework>

값을 따르는데요, 만약 이 경로를 없애고 싶다면 AppendTargetFrameworkToOutputPath 옵션을 false로 설정하시면 됩니다.

<TargetFramework>net7.0</TargetFramework>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>

이후 빌드하면 출력 디렉터리가 다음과 같이 바뀝니다.

C:\temp\ConsoleApp1\ConsoleApp1\bin\Debug\ConsoleApp1.dll




자, 그럼 여기서 bin 디렉터리도 지워볼까요? ^^ 이를 위해 BaseOutputPath를 지정할 수 있습니다. (이 값은 비주얼 스튜디오의 프로젝트 속성창을 통해서도 설정할 수 있습니다.)

<TargetFramework>net7.0</TargetFramework>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<BaseOutputPath>.\</BaseOutputPath>

빌드하면 다음과 같이 출력 디렉터리가 생기는데요,

C:\temp\ConsoleApp1\ConsoleApp1\Debug\ConsoleApp1.dll

대신 부작용이 하나 있습니다. 빌드하자마자 현재 프로젝트 경로의 하위에 Debug 폴더가 생성되고 Visual Studio의 Solution Explorer에는 다음과 같이 "Debug" 디렉터리가 나오게 됩니다.

output_path_option_1.png

그래서 이 디렉터리를 없애기 위해 별도의 ItemGroup을 포함시켜야 합니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <BaseOutputPath>.\</BaseOutputPath>
    </PropertyGroup>

    <ItemGroup>
      <Compile Remove="Debug\**" />
      <EmbeddedResource Remove="Debug\**" />
      <None Remove="Debug\**" />
    </ItemGroup>

</Project>




혹시 "Debug"도 제거할 수 있을까요? 아쉽게도 제가 아는 범위 내에서는 그런 옵션은 없습니다. 단지, 아예 Output 경로를 완전히 새롭게 지정하는 방법이 있는데요, 바로 OutputPath를 지정하는 것입니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <OutputPath>.\</OutputPath>
    </PropertyGroup>

</Project>

이렇게 되면 현재 프로젝트와 동일한 경로에 출력 파일들이 함께 놓이므로,

C:\temp\ConsoleApp1\ConsoleApp1> dir /b
ConsoleApp1.csproj
ConsoleApp1.deps.json
ConsoleApp1.dll
ConsoleApp1.exe
ConsoleApp1.pdb
ConsoleApp1.runtimeconfig.json
obj
Program.cs

번잡해지는 단점이 있습니다. 물론, 사실 저런 식으로 쓰는 경우는 거의 없을 것입니다. 그보다는 절대 경로를 지정해 출력하는 경우 편리하게 사용할 수 있습니다.

<OutputPath>c:\tools</OutputPath>

저렇게 되면 bin 디렉터리와 Debug/Release와 연관된 디렉터리 설정을 모두 무시하게 되는데요, 만약 그것을 살리고 싶다면 관련 속성을 추가해 제어할 수 있습니다.

// c:\temp\bin\Debug 또는 c:\temp\bin\Release
<OutputPath>c:\temp\bin\$(Configuration)</OutputPath>




이 외에도, 아래의 문서를 보면,

How to: Change the build output directory
; https://learn.microsoft.com/en-us/visualstudio/ide/how-to-change-the-build-output-directory

AppendRuntimeIdentifierToOutputPath, UseCommonOutputDirectory, IntermediateOutputPath 3가지 옵션이 나옵니다. 하나씩 알아볼까요? ^^

우선 AppendRuntimeIdentifierToOutputPath 옵션 먼저 보겠습니다. 실습을 위해 기본 C# Console 응용 프로그램에 다음이 옵션을 추가합니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <RuntimeIdentifier>linux-x64</RuntimeIdentifier>
    </PropertyGroup>

</Project>

이후 해당 프로젝트를 빌드하면 "bin/Debug/net7.0" 뿐만 아니라 추가로 "linux-x64"가 출력 디렉터리에 따라붙게 됩니다.

C:\temp\ConsoleApp1\ConsoleApp1\bin\Debug\net7.0\linux-x64\ConsoleApp1.dll

바로 저 "linux-x64", 즉 RuntimeIdentifier 옵션이 지정돼 붙게 되는 경로를 무시할 수 있는 옵션이 바로,

<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>

AppendRuntimeIdentifierToOutputPath가 되겠습니다. 따라서 위의 설정에서 빌드를 하게 되면 linux-x64 디렉터리가 없어집니다.

C:\temp\ConsoleApp1\ConsoleApp1\bin\Debug\net7.0\ConsoleApp1.dll




UseCommonOutputDirectory는 이름이 다소 혼란스럽습니다. 그냥 그 옵션만 설정하면 솔루션 파일이 위치한 디렉터리를 기준으로 포함된 프로젝트들의 출력을 모두 모아줄 것 같은데, 사실은 그런 기능과 아무런 상관이 없습니다.

이 옵션이 하는 역할은, 단지 빌드 시스템에게 해당 프로젝트들이 출력 디렉터리를 공유할 것이라고 알려주는 것에 불과합니다. 그렇다면, 왜 이게 필요한 것일까요?

예를 들어, 다음과 같은 식으로 솔루션/프로젝트를 구성하고,

.\ConsoleApp1.sln
    \ConsoleApp1\ConsoleApp1.csproj
    \ClassLibrary1\ClassLibrary1.csproj

이때 ConsoleApp1 프로젝트가 ClassLibrary1 프로젝트를 참조한다고 가정해 보겠습니다. 이 상태에서 Console 프로젝트를 빌드하면 당연히 출력 디렉터리에 라이브러리 DLL이 함께 출력이 됩니다.

하지만, 만약에 이런 상태에서 2개의 프로젝트가 아래처럼 같은 Output 디렉터리로 출력하라고 지정했다면 어떻게 될까요?

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <OutputPath>c:\temp\$(Configuration)</OutputPath>
    </PropertyGroup>

    <ItemGroup>
      <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" />
    </ItemGroup>

</Project>

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>

        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <OutputPath>c:\temp\$(Configuration)</OutputPath>
    </PropertyGroup>

</Project>

그럼 2개의 프로젝트 빌드 결과가 c:\temp\Debug 디렉터리에 모이게 되는데요, 문제는 이런 상황에서 비주얼 스튜디오는 ClassLibrary1 프로젝트가 빌드됐을 때 온전히 c:\temp\Debug 디렉터리에 출력이 모였음에도 불구하고, 이어서 ConsoleApp1 프로젝트가 빌드되면서 다시 프로젝트를 c:\temp\Debug로 복사하는 시도를 한다는 것입니다.

사실 필요 없는 절차이지만, 게다가 워낙 복사 과정이 빠르기 때문에 굳이 신경 쓰지 않아도 되지만 이런 과정을 생략하도록 지정할 수 있는 옵션이 UseCommonOutputDirectory입니다. 이 옵션을 2개의 프로젝트 모두에 설정해 주면,

<UseCommonOutputDirectory>true</UseCommonOutputDirectory>

이후 빌드에서는 ConsoleApp1 프로젝트가 ClassLibrary1 프로젝트의 출력 결과물을 복사해 오는 과정을 (빌드 시스템이 알고 있으므로) 생략하게 됩니다.




마지막으로 IntermediateOutputPath 옵션은 직접적인 출력 디렉터리와는 상관없고 단지 중간 출력 결과물의 생성 경로를 바꿀 수 있습니다. 이 옵션이 없다면 ./obj 디렉터리 하위에 Debug(또는 Release) 디렉터리가 생겨 중간 출력물을 그곳에 생성하는데, IntermediateOutputPath를 지정하게 되면 Debug(또는 Release) 디렉터리를 없애고 새롭게 설정하는 것이 가능합니다.

문서에 보면,

Visual Studio still creates the obj folder under the project folder when you build, but it's empty.


IntermediateOutputPath를 지정한 경우, ./obj 디렉터리는 (비어 있지만) 그래도 생성된다고 합니다. 그런데, .NET 7 환경에서 테스트하면 obj 디렉터리에는 다음의 파일들이 출력됩니다.

C:\temp\ConsoleApp1\ConsoleApp1\obj> dir /b
ConsoleApp1.csproj.nuget.dgspec.json
ConsoleApp1.csproj.nuget.g.props
ConsoleApp1.csproj.nuget.g.targets
project.assets.json
project.nuget.cache

즉, 비어 있지도 않으므로 현재로서는 어떻게 해도 저 ./obj 디렉터리를 옵션으로 지울 수 있는 방법은 없습니다. 단지, 문서에도 언급하듯이 PostBuildEvent를 설정해 삭제하는 식으로 우회할 수는 있습니다.

<PostBuildEvent>rd "$(MSBuildProjectDirectory)\obj" /s /q</PostBuildEvent>

참고로, ".NET SDK 6.0.200"부터는 참조 어셈블리도 IntermediateOutputPath 하위에 복사되도록 바뀌었습니다.

Write reference assemblies to intermediate output
; https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/6.0/write-reference-assemblies-to-obj

그래서 ./obj/Debug 하위에 ref, refint 디렉터리가 함께 생성되고 그 안에 Reference assembly가 생성됩니다. 이유는 알 수 없지만, ref와 refint에 포함된 참조 어셈블리는 동일한 파일인데요, ref 디렉터리는 .NET 5.0 이하에서 쓰던 디렉터리 이름인 반면 "refint"는 IntermediateOutputPath 경로로 바뀌면서 변경된 이름입니다.

참조 어셈블리가 굳이 필요하지 않다면 ProduceReferenceAssembly를 설정해,

<ProduceReferenceAssembly>false</ProduceReferenceAssembly>

ref, refint 디렉터리 모두 없앨 수 있습니다.




개인적으로 위의 내용에서 한 가지 사용처를 하나 발견했습니다. 제 경우에, ^^ 보통 블로그를 쓸 때, 백업을 위해 dropbox 디렉터리에서 프로젝트를 생성하게 되는데요, 문제는 빌드 때마다 쓸데없는 파일들이 모두 동기화된다는 점입니다.

그래서, 앞으로는 다음과 같이 구성해 두려고 합니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>

        <BaseOutputPath>c:\temp\prj\$(MSBuildProjectName)</BaseOutputPath>
        <IntermediateOutputPath>$(BaseOutputPath)\obj</IntermediateOutputPath>
        
        <PostBuildEvent>rd "$(MSBuildProjectDirectory)\obj" /s /q</PostBuildEvent>
    </PropertyGroup>

</Project>

위의 설정으로 빌드하는 경우 /obj 디렉터리는 삭제되고, /bin 디렉터리는 c:\temp\prj 디렉터리로 모이게 됩니다. 따라서 프로젝트 디렉터리에는 다음과 같이 최소한의 파일만 남게 됩니다.

C:\temp\ConsoleApp1\ConsoleApp1> dir /b
ConsoleApp1.csproj
Program.cs

깔끔하죠? ^^ 이제 해당 디렉터리만 바로 압축해 블로그의 글에 첨부하면 됩니다.

끝으로, 위의 구성으로 "프로젝트 템플릿"을 하나 만들어 재활용하면 되겠습니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/4/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13432정성태10/31/20232453오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232790스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232678닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232960닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233035닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233249닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233408스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233195닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233173스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233318닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233395닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235583스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233219스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233924닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233454닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233259오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233756닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233514디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233710닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236991닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233492Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235031닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233887닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233843Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233588닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233557VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...