본문 바로가기
IT/c, c++

VSCode 에서 pthread 사용하는 방법

by TechTonic 2022. 12. 9.
반응형

VSCode IDE 툴에서 pthread 를 사용하는 방법에 대해 공유 합니다.

 

VSCode 설치 후 c/c++ 컴파일러가 설치된 상태에서의 내용이므로

아래 내용을 참고하여 c/c++ 컴파일러까지 설치하시기 바랍니다.

2022.12.09 - [IT/c, c++] - Visual Studio Code C/C++ 환경 구축 #Feat. VScode

 

Visual Studio Code C/C++ 환경 구축 #Feat. VScode

VScode IDE 툴을 사용하여 c/c++ 코딩 환경을 구축해보려 합니다. 1. VScode 실행 후 [확장] 메뉴를 통해 아래 패키지 설치 C/C++ C/C++ Extension Pack 2. 윈도우에서 컴파일을 위한 MinGW 설치 아래 사이트에 접

soir1984.tistory.com

 

 

에러내용

 

위 환경을 구성한 뒤 c파일 코드에 #include <pthread.h> 를 선언하면 에러 표시가 발생됩니다.

이는 pthread.h 헤더를 찾지 못해 발생하는 내용입니다.

에러 화면

아래는 빌드 시 pthread 를 사용하는 코드에서 undefined 가 발생됨이 확인됩니다.

빌드를 시작하는 중...
C:\MinGW\bin\gcc.exe -fdiagnostics-color=always -g D:\05.VSCODE\c\hello.c -o D:\05.VSCODE\c\hello.exe
C:\Users\Soo\AppData\Local\Temp\ccoNUC8n.o: In function `count':
D:/05.VSCODE/c/hello.c:16: undefined reference to `pthread_mutex_lock'
D:/05.VSCODE/c/hello.c:29: undefined reference to `pthread_mutex_unlock'
C:\Users\Soo\AppData\Local\Temp\ccoNUC8n.o: In function `main':
D:/05.VSCODE/c/hello.c:38: undefined reference to `pthread_mutex_init'
D:/05.VSCODE/c/hello.c:40: undefined reference to `pthread_create'
D:/05.VSCODE/c/hello.c:41: undefined reference to `pthread_create'
D:/05.VSCODE/c/hello.c:43: undefined reference to `pthread_join'
D:/05.VSCODE/c/hello.c:44: undefined reference to `pthread_join'
D:/05.VSCODE/c/hello.c:46: undefined reference to `pthread_mutex_destroy'
collect2.exe: error: ld returned 1 exit status

 

해당 오류는 pthread.h path를 잡아주면 되며, 

추가로, path를 잡아주더라도 나중에 빌드 시 오류가 발생됩니다.

빌드 시 발생하는 이유는 pthread 를 사용할 경우 컴파일러 argment 에 "-pthread" 옵션을 추가해주어야 하는데

기본 설정에는 없어 빌드 옵션에 추가하는 작업도 포함되어야 합니다.

 

 

 

해결책

 

1. pthread.h 헤더 path 추가하기

위 링크에서 설치한 MinGW 설치 디렉토리를 찾아둡시다.

그리고 현재 사용중인 프로젝트 폴더에 보시면 .vscode 폴더가 있습니다.

.vscode 폴더 내부의 "c_cpp_properties.json" 파일을 열어 아래 내용을 추가해줍니다.

  • "C:\\MinGW\\include\\**"
  • "compilerArgs": ["-pthread"]

아래는 전체 내용입니다.

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:\\MinGW\\include\\**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-msvc-x64",
		"compilerArgs": [
			"-pthread"
		]
			
        }
    ],
    "version": 4
}

 

해당 코드를 적용하면 코드에서 에러 표시들이 사라집니다.

하지만 빌드 시 동일하게 pthread 관련 코드에서 undefined 오류가 발생됩니다.

 

 

 

2. 빌드 커맨드에 -pthread 옵션 추가하기

위에서 언급한 바와 같이 pthread 사용할 경우 빌드 시 -pthread 옵션을 추가해서 빌드해야 합니다.

자신이 생성한 tasks.json 파일을 열어봅니다.

tasks.json 파일의 args에  "-pthread" 를 추가합니다.

아래는 tasks.json 전체 코드 입니다.

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: gcc.exe 활성 파일 빌드",
			"command": "C:\\MinGW\\bin\\gcc.exe",
			"args": [
				"-fdiagnostics-color=always",
				"-g",
				"-pthread",
				"${file}",
				"-o",
				"${fileDirname}\\${fileBasenameNoExtension}.exe"
			],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "test",
				//"isDefault": true
			},
			"detail": "컴파일러: C:\\MinGW\\bin\\gcc.exe"
		},
		// 파일 실행
		{
			"label": "execute",
			"command": "cmd",
			"group": "test",
			"args": [
			  "/C",
			  "${fileDirname}\\${fileBasenameNoExtension}"
			]
		  }
	]
	
}

 

해당 코드 -pthread 삽입 후 빌드 시 정상적으로 수행됨을 확인 할 수 있습니다.

///////////////////////////////////////////
// pthread 옵션 미 설정 시 오류
///////////////////////////////////////////
빌드를 시작하는 중...
C:\MinGW\bin\gcc.exe -fdiagnostics-color=always -g D:\05.VSCODE\c\hello.c -o D:\05.VSCODE\c\hello.exe
C:\Users\Soo\AppData\Local\Temp\ccWdcwA7.o: In function `count':
D:/05.VSCODE/c/hello.c:16: undefined reference to `pthread_mutex_lock'
D:/05.VSCODE/c/hello.c:29: undefined reference to `pthread_mutex_unlock'
C:\Users\Soo\AppData\Local\Temp\ccWdcwA7.o: In function `main':
D:/05.VSCODE/c/hello.c:38: undefined reference to `pthread_mutex_init'
D:/05.VSCODE/c/hello.c:40: undefined reference to `pthread_create'
D:/05.VSCODE/c/hello.c:41: undefined reference to `pthread_create'
D:/05.VSCODE/c/hello.c:43: undefined reference to `pthread_join'
D:/05.VSCODE/c/hello.c:44: undefined reference to `pthread_join'
D:/05.VSCODE/c/hello.c:46: undefined reference to `pthread_mutex_destroy'
collect2.exe: error: ld returned 1 exit status

빌드가 완료되었지만, 오류가 발생했습니다.

 *  The terminal process terminated with exit code: -1. 
 *  Terminal will be reused by tasks, press any key to close it. 

 *  Executing task: C/C++: gcc.exe 활성 파일 빌드 

///////////////////////////////////////////
// pthread 옵션 설정 시 빌드 성공
///////////////////////////////////////////
빌드를 시작하는 중...
C:\MinGW\bin\gcc.exe -fdiagnostics-color=always -g -pthread D:\05.VSCODE\c\hello.c -o D:\05.VSCODE\c\hello.exe

빌드가 완료되었습니다.

 

 

 

 

반응형

댓글