개발/정보처리기사

Mac OS (M1)에 C언어 개발환경 구축하기

김현중 (keemhing) 2024. 9. 30. 18:46

정보처리기사 필기 합격 이후 실기 시험 준비 중이다. 사실 실기시험을 한번 봤는데.. 떨어졌다... JAVA로만 개발 공부를 진행했던지라 프로그래밍 언어 부분이 너무 어려웠다. 다시 실기시험을 준비하면서 책이나 문제집만 풀어보는 게 아니라 C, C++, C#, python 등의 언어로 직접 코드를 작성해 보고 컴파일시켜 결괏값을 확인하면서 공부하려고 한다. (조금이나마 더 도움이 되리라 판단했다)

 

Mac OS 환경에서 C언어를 사용하는 방법 중 가장 확실한 방법으로는 Visaul Studio Tool을 사용하는 방법이 있으나 아쉽게도... 2024년 08월 31일에 서비스가 종료되었다. (마이크로소프트에서 공식으로 발표했다.)

 

그래서 필자는 Visual Studio Code Tool을 사용하는 방법으로 C언어 개발환경을 구축하려한다. 차근차근 하나씩 하면 금방 구축할 수 있다.

 


Visual Studio Code 설치

사이트에 접속하여 본인 컴퓨터 환경에 맞는 버전으로 다운받으면다운로드하면 된다.(Intel 칩이면 Intel, M 시리즈 칩이면 Apple Silicon 버전으로 다운로드하면 된다)

 

>> https://code.visualstudio.com/download <<

 


Extension 설치 (확장 도구 설치)

왼쪽 배너에 귀여운 레고같은 배너를 클릭하면 Extension을 검색할 수 있는 창으로 바뀐다.


1.  C/C++ 

언어에 대한 Extension을 설치한다.

2. Code Runner 

 

코드를 실행시켜주는 확장 도구를 설치해 준다. 그리고 추가적인 설정을 해줘야 한다. Code Runner 확장도구 아래에 톱니바퀴를 누르고 Extension Settiongs을 클릭한다.

 

다음 화면으로 넘어가지면 Edit in settings.json을 클릭한다.

 

작성되어있는 파일에 아래 코드를 추가해 준다. 

    "git.ignoreMissingGitWarning": true,
    "code-runner.runInTerminal": true,      
    "C_Cpp.updateChannel":"Insiders",
    "editor.multiCursorModifier": "ctrlCmd",
    "C_Cpp.default.cppStandard": "c++17",
    "C_Cpp.default.cStandard": "c11",

 

As-Is

{
    "editor.minimap.enabled": false,
    "git.openRepositoryInParentFolders": "never",
    "editor.stickyScroll.enabled": false,
    "explorer.confirmPasteNative": false,
    "explorer.confirmDelete": false,
    "explorer.confirmDragAndDrop": false,
    "liveServer.settings.donotShowInfoMsg": true,
    "code-runner.executorMap": {

        
        "javascript": "node",
        
        .
        .
        .
        (생략)

 

To-Be

{
    "git.ignoreMissingGitWarning": true,
    "code-runner.runInTerminal": true,      
    "C_Cpp.updateChannel":"Insiders",
    "editor.multiCursorModifier": "ctrlCmd",
    "C_Cpp.default.cppStandard": "c++17",
    "C_Cpp.default.cStandard": "c11",
    
    "editor.minimap.enabled": false,
    "git.openRepositoryInParentFolders": "never",
    "editor.stickyScroll.enabled": false,
    "explorer.confirmPasteNative": false,
    "explorer.confirmDelete": false,
    "explorer.confirmDragAndDrop": false,
    "liveServer.settings.donotShowInfoMsg": true,
    "code-runner.executorMap": {
    
        
        "javascript": "node",

        .
        .
        .
	    (생략)

 

코드 작성후 반드시 저장해줘야 한다!! 그러고 나서 Command + k + s 키를 눌러 코드를 실행하는 단축키를 설정한다. 편한 거로 설정하면 된다. 

3. CodeLLDB (디버깅을 해줄 확장 도구)

 

CodeLLDB를 설치했다면 본인이 공부할 디렉토리를 생성하고 그 폴더를 열어 .c 파일을 하나 생성한다.

 

이 작업을 하지 않으면 디버깅 배너를 클릭했을 때 아래와 같이 뜬다. (create a launch.json file 이라는 문구가 보여야 한다.)

 

폴더를 열어 .c 파일 생성을 했다면 아래와 같이 보일 것이다.

출처 : https://songacoding.tistory.com/49

 

저 문구가 보인다면 클릭해 주자. 파일이 생성되고 오픈되었을 것이다. 기존 내용을 전부 지워버리고 아래 코드로 교체해 주자.

{
    "version": "0.2.0",
    "configurations": [

        {
            "type": "lldb",
            "request": "launch",
            "name": "Lldb debug",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "cwd": "${workspaceRoot}"
        }
    ]
}

 

이제 컴파일할 때 사용할 세팅값을 설정할 것이다. (tasks.json 파일 생성) 

 

Visual Studio Code 상단에 Terminal 배너에서 Configure Tasks ... 를 선택한다.

 

Create tasks.json file from template을 클릭해 준다.

출처 : https://songacoding.tistory.com/49

 

Other를 클릭해 주면 tasks.json 파일이 생성된다.

출처 : https://songacoding.tistory.com/49

 

tasks.json 파일의 내용을 아래 코드로 전부 교체해 준다.

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "C bulid for clang",
            "command": "clang",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "presentation": {
                "clear": true
            },
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": []
        },
        {
            "type": "shell",
            "label": "C++ bulid for clang++",
            "command": "clang++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "presentation": {
                "clear": true
            },
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": []
        },
        {
            "type": "shell",
            "label": "execute",
            "command": "${fileDirname}/${fileBasenameNoExtension}",
            "group": "test",
            "presentation": {
                "clear": true
            }
        }
    ]
}

 

이제 진짜 다 왔다. 조금만 힘내자. Command + shift + b를 눌러 빌드를 실행해 보자. C언어로 실행할 것이니,  C build for clang을 선택해 준다.

출처 : https://songacoding.tistory.com/49


 

C/C++ 컴파일러 설치 (homebrew & xcode)

맥북에서 terminal 실행하고 아래 코드 그대로 복사 & 붙여 넣기 하여 설치해 준다.

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

 

그럼 이런 내용이 나올 텐데...

==> Checking for `sudo` access (which may request your password)...
Password:

 

맥북 잠금 해제할 때 사용하는 비밀번호 입력하고 엔터 누른다. (비밀번호를 입력해도 뭔가 보이지는 않는다. 잘못 눌렀다면 지우고 다시 작성하면 된다. )

 

아래와 같은 문구가 나오면 한번 더 엔터를 눌러주자.

Press RETURN/ENTER to continue or any other key to abort:

 

이제 알아서 설치가 될 것이다. 시간이 좀 지나고 아래와 같은 문구가 나오면 설치가 완료된 것이다.

...
==> Next steps:
- Run these two commands in your terminal to add Homebrew to your PATH:
    echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/songa/.zprofile
    eval "$(/opt/homebrew/bin/brew shellenv)"
- Run brew help to get started
- Further documentation:
    https://docs.brew.sh

 

터미널에 gcc -v 입력하여 정보를 확인해 보자. 아래와 같이 나온다면 성공한 것이다.

Apple clang version 13.1.6 (clang-1316.0.21.2.5)
Target: arm64-apple-darwin21.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

 


C언어로 Hello World! 띄워보기

프로그래밍 언어 배울 때 가장 기본으로 하는... 콘솔에 Hello World 띄우기를 한번 해보자. Hello World.c 파일을 생성하고 코드를 작성해 준다. 그리고 Control + option + n 눌러서 파일을 Run 해보면...

 

이렇게 콘솔에 문자열이 잘 뜬다! 

 

공부 열심히 해서 정보처리기사 자격증 취득하자.. 모두모두 파이팅..!

 

참고한 블로그 - 송아지할때송아김송아입니다