Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 10개 있습니다.)

Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록

C++ thread 객체를 사용했을 때,

#include <thread>
    thread t([&]()

다음과 같은 링크 오류가 발생하는 경우,

Error undefined reference to symbol 'pthread_create@@GLIBC_2.4'
Error DSO missing from command line
Error ld returned 1 exit status

"Configuration Properties" / "Linker" 범주의 "Command Line" 설정에 -pthread 옵션을 추가하는 것으로 해결.




다음과 같은 빌드 오류가,

Error C1020 unexpected #endif

stdafx.h 헤더 파일을 포함하는 코드에서 발생한다면?

#if defined(WIN32)
#include "stdafx.h"
#endif

stdafx.h 헤더 파일이 특별하기 때문입니다. pre-compiled 헤더 파일의 포함 유무 선택은(#if/#endif) 가능하지 않습니다.




Socket의 bind 함수를 추가했는데,

int ret = bind(_sock, (struct sockaddr*)&_server_addr, addr_len);

다음과 같은 오류가 발생한다면?

Error C2440 'initializing': cannot convert from 'std::_Binder<std::_Unforced,int &,sockaddr *,int &>' to 'int'

C++의 bind 함수와 중복되었기 때문입니다. 이런 경우에는 Socket의 bind에 전역 심벌 사용을 명시하면 됩니다.

int ret = ::bind(_sock, (struct sockaddr*)&_server_addr, addr_len);




소켓 사용 시 다음과 같은 오류가 발생한다면?

Error LNK2019 unresolved external symbol ___WSAFDIsSet@8 referenced in function "public: void __thiscall <lambda_5b230eb5c4ebbd478baf88927e86c7be>::operator()(void)const " (??R<lambda_5b230eb5c4ebbd478baf88927e86c7be>@@QBEXXZ)

ws2_32.lib를 import합니다.

#pragma comment(lib, "ws2_32.lib")




socket 함수가 -1을 반환한다면?

_sock = socket(AF_INET, SOCK_DGRAM, 0);

혹시 WSAStartup 호출을 하셨나요? ^^ linux의 경우 소켓 관련 초기화를 할 필요가 없어 자칫 윈도우 용 소스 코드에 누락시켰을 수 있습니다.

#if defined(WIN32)
    WORD wVersionRequested = MAKEWORD(2, 2);
    WSADATA wsaData;

    ::WSAStartup(wVersionRequested, &wsaData);
#endif

    // ... _sock = socket( ... );

#if defined(WIN32)
    WSACleanup();
#endif




samba로 공유시킨 폴더에 윈도우로 접근한 후, notepad를 이용해 .sh 파일을 만든 후 라즈베리 파이에서 실행했더니 다음과 같은 오류가 발생합니다.

$ /share/dual.sh
sudo: unable to execute /share/dual.sh: No such file or directory

리눅스는 execute 권한이 없는 파일을 실행하는 경우 "No such file or directory"라는 오류가 발생합니다. 따라서 다음과 같이 실행 권한을 줘야 합니다.

$ chmod +x /share/dual.sh

또는 이런 오류가 발생할 수도 있습니다.

$ /share/dual.sh
-bash: ./dual.sh: /bin/bash^M: bad interpreter: No such file or directory

왜냐하면 윈도우에서는 개행을 \r\n으로 하지만 리눅스의 경우에는 \n 하나이기 때문입니다. 이미 복사된 환경에서 \r\n을 \n으로 바꿔서 저장하고 싶다면 dos2unix라는 도구를 이용하면 됩니다.

$ sudo apt-get install dos2unix

$ dos2unix dual.sh

또는 Visual Studio와 같은 편집기에서는 "File" / "Save As..." 명령어를 이용해 "Save with Encoding..." 옵션으로 "Line endings"를 "Unix (LF)"로 바꿔 저장하면 됩니다.




리눅스에서는 (Socket을 포함해) File Descriptor에 대한 접근을 잘못하는 경우 "Access Violation" 오류가 발생할 수 있습니다. 가령 다음과 같은 예제를 보면,

struct sockaddr_in server_socket;
socklen_t addr_len = sizeof(server_socket);

int clntSocket = accept(_sock, (struct sockaddr *)&server_socket, &addr_len);

thread clntThread([&]()
{
    char buf[4096] = { 0 };
    int recvBytes = recv(clntSocket, buf, 4096 - 1, 0);
    send(clntSocket, buf, recvBytes, 0);
    closesocket(clntSocket);
});

clntThread.detach();

send 함수 실행에서 다음과 같은 오류와 함께 프로그램이 비정상 종료합니다.

Exception thrown: read access violation.
this->clntSocket was 0x319F500.

왜냐하면, 새롭게 생성된 clntThread보다 먼저 clntSocket 변수가 scope을 벗어났기 때문에 참조(&) 값으로 전달받았던 clntSocket 변수의 값이 스택 변경에 따라 쓰레기 값으로 바뀐 탓입니다. 이런 경우에는 clntSocket 변수에 대한 캡처 방식을 참조가 아닌 복사로 처리하면 됩니다.

struct sockaddr_in server_socket;
socklen_t addr_len = sizeof(server_socket);

int clntSocket = accept(_sock, (struct sockaddr *)&server_socket, &addr_len);

thread clntThread([=]()
{
    char buf[4096] = { 0 };
    int recvBytes = recv(clntSocket, buf, 4096 - 1, 0);

    printf("%s", buf);

    send(clntSocket, buf, recvBytes, 0);
    closesocket(clntSocket);
});

clntThread.detach();




참고로, 람다 함수내에서 참조하는 변수를 명시하지 않으면 이런 컴파일 에러가 발생합니다.

Error E1735 an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list

잊지 말고 캡처 변수를 명시하거나 "[&]", "[=]"와 같이 자동 처리하면 됩니다.

그런데, this 포인터를 람다 함수에서 쓰고 싶다면 어떻게 해야 할까요? 그냥 쓰려고 하면 다음과 같은 오류가 발생합니다.

Error C4573 the usage of '...' requires the compiler to capture 'this' but the current default capture mode does not allow it

그렇다고, [&]로 모든 변수를 캡처하고 싶지도 않다면 다음과 같이 this 포인터를 전달할 수 있습니다.

thread clntThread([this](int connectedSocket)




"Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작"을 하다가 헤더 파일을 include하는 곳에서,

#include "stdafx.h"
#include "VUsbServer.h" // 여기서 "No such file or directory" 에러

다음과 같은 오류가 발생할 수 있습니다.

Error VUsbServer.h: No such file or directory
Error Access to the path 'C:\rasp_vusb\rasp_vusb_server\obj\ARM\Debug\-1607192315.CompileUpToDateFile.tlog' is denied.

분명히 VUsbServer.h 파일이 라즈베리 파이에 정상적으로 복사되어 있는데도 저런 오류가 발생한다면 파일명의 대/소문자까지 맞는지 확인해야 합니다. 윈도우와는 달리 리눅스는 대/소문자까지 일치해야 합니다.




라즈베리 파이에 /etc/dhcp/dhcpd.conf 파일을 이용해 정적 IP 할당 후,

interface wlan0
 static ip_address=192.168.0.50/24
 static routers=192.168.0.1
 static domain_name_servers=164.124.101.2

DNS 이름 풀이를 하는 경우 "Temporary failure in name resolution" 오류가 발생한다면?

$ ping www.sysnet.pe.kr
ping: www.sysnet.pe.kr: Temporary failure in name resolution

물론 domain_name_servers에 지정한 IP가 올바른지도 봐야겠지만, "routers"의 항목도 맞는지 확인을 해야 합니다. 윈도우의 경우 ipconfig으로 보면 "Default Gateway"라는 항목의 IP 주소를 "routers"에 입력해야 하는데요. 습관적으로(?) "xxx.xxx.xxx.1"이라고 지정하면 안됩니다. 경우에 따라 "xxx.xxx.xxx.254"이거나 다른 IP로 얼마든지 설정될 수 있기 때문입니다.



윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법
; https://www.sysnet.pe.kr/2/0/11372

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 이더넷 카드로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11353

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11354

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11355

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11356

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표)
; https://www.sysnet.pe.kr/2/0/11364

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠)
; https://www.sysnet.pe.kr/2/0/11369

라즈베리 파이 용 C++ 프로젝트에 SSL Socket 적용
; https://www.sysnet.pe.kr/2/0/11411

Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
; https://www.sysnet.pe.kr/2/0/11373

Linux 3: 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정
; https://www.sysnet.pe.kr/2/0/11374


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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2021]

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)
13322정성태4/15/20234936VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233735개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233740개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234181개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20233989개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234146오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233473오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233667Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233743개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233836개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233822Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234317C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20233879C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234034.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20233924스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233720.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233568Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20233907Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234263VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233565Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234182Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234319Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20233950Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233736Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233675Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234350Windows: 235. Win32 - Code Modal과 UI Modal
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...