2023년 11월 15일 수요일

MSVC command line 빌드 예

Visual Studio

  • 글 작성 기준 visual studio 2022

설치 완료 시 프로그램 -> Visual Studio 2022 에 여러 프롬프트 제공

 

호스트 PC 64 또는 32비트 개발 환경 선택 가능
  • x64 Native Tools Command Prompt for VS 2022
  • x86 Native Tools Command Prompt for VS 2022
예)


개발 프롬프트를 열면 개발에 필요한 도구를 바로 사용할 수 있게 환경 변수들이 자동 세팅됨
  • cl.exe
  • lib.exe
  • link.exe
  • nmake.exe

 

기본 (실행 프로그램 빌드)


e.g.) main.c


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    printf("Hello\n");
    return 0;
}

 

빌드

> cl /Fe:main.exe main.c

  • /Fe:main.exe 빌드 결과물 이름을 main.exe 로 설정


실행

> main.exe


Makefile (nmake)

e.g.) Makefile

all: main.exe

main.exe: main.c
    cl /Fe:$@ $**

clean:
    del main.exe *.obj


nmake 수행

> nmake

또는 실행 타겟 지정 (예: clean)

> nmake clean

또는 makefile 파일명이 다르다면 (예: Makefile.nmake)

> nmake /f Makefile.nmake


라이브러리 빌드


e.g.) hello.c

#include <stdio.h>
#include "hello.h"

void hello(void)
{
    printf("Hello world!\n");
}


e.g.) hello.h

#ifndef __HELLO_H__
#define __HELLO_H__

#ifdef __cplusplus
extern "C" {
#endif

  __declspec(dllexport) void hello(void);

#ifdef __cplusplus
}
#endif

#endif


빌드

> cl /LD hello.c


빌드 결과물

  • hello.dll 동적 라이브러리
  • hello.lib 정적 라이브러리


e.g.) main.c

#include <hello.h>

int main(int argc, char *argv[])
{
  hello();
  return 0;
}


빌드 (링크 포함)

> cl /Fe:main.exe main.c /I . /link hello.lib

  • /I . 현재 위치 (.) 을 헤더 검색 위치에 추가
  • /link link 옵션 시작
    • /link hello.lib 정적 라이브러리 (hello.lib) 을 링크에 추가 



컴파일과 링크 따로 하기


e.g.) a.c

#include <stdio.h>

extern void a(void)
{
    printf("a\n");
}

 

e.g.) b.c

#include <stdio.h>

extern void b(void)
{
    printf("b\n");
}

 

e.g.) c.c

#include <stdio.h>

extern void a(void);
extern void b(void);

extern void c(void)
{
    printf("c\n");
}


int main(int argc, char *argv[])
{
    a();
    b();
    c();
    return 0;
}


컴파일

> cl /c a.c b.c c.c 

  • 결과물
    • a.obj
    • b.obj
    • c.obj


링크

> link a.obj b.obj c.obj /OUT:program.exe

  • 결과물
    • program.exe


실행

> program
a
b
c


라이브러리 검색 경로 설정 (/LIBPATH:<dir>)


e.g.) SDL2 빌드 Makefile 예제

https://github.com/bjtj/tjsamples/blob/master/sdl2/hello/Makefile.nmake

all: hello.exe

hello.exe: main.obj
    link /OUT:$@ /LIBPATH:SDL2-2.28.5/lib/x64 main.obj SDL2.lib SDL2main.lib shell32.lib /SUBSYSTEM:WINDOWS

main.obj: main.c
    cl /I ./SDL2-2.28.5/include /c $**

clean:
    del *.obj hello.exe

.PHONY: all clean


설명

  • /LIBPATH:SDL2-2.28.5/lib/x64
    • /LIBPATH:<dir> 형태로 검색 경로가 복수개 존재하면 복수개 입력
    • e.g.) /LIBPATH:<dir1> /LIBPATH:<dir2> ...


LINKER 옵션

https://learn.microsoft.com/en-us/cpp/build/reference/linker-options?view=msvc-170


댓글 없음:

댓글 쓰기