.cpp
개 파일의 변수에 액세스하고 싶습니다. 나는 여러 가지 자료를 조사했다. 나는 그것을 해결할 수 없었다. 이 프로젝트의 모든 코드를 빌드하는 데 cmake
을 사용하고 있습니다. 다음은 정확하게 내 문제와 일치하는 예제입니다. 기본적으로 val
은 code1.cpp
과 code2.cpp
에서 42를 인쇄하고 싶습니다. 이 세 파일을 빌드 할 때 불평 : undefined reference to 'he::val' collect2: error:ld returned 1 exit status
.cpp 파일 모두에 대해.mumtiple cpp 파일의 변수에 액세스하는 방법은 각 파일의 기본 섹션을 포함합니까?
header1.h
#ifndef HEADER1_H
#define HEADER1_H
#include <iostream>
namespace he {
extern int val;
}
#endif // HEADER1_H
code1.cpp
#include "header1.h"
#include <iostream>
using namespace he;
int func()
{
std::cout << val << std::endl;
}
int main()
{
val=20;
func();
return 0;
}
code2.cpp
#include <iostream>
#include "header1.h"
using namespace he;
int main()
{
std::cout << val << std::endl;
}
그럼 어떻게 변수를 공유 할 수 있습니까? 다른 대안이 있습니까? –
두 cpp 파일 사이에서 변수를 공유하려면 하나의 변수에 정의하고 다른 변수에 extern으로 선언하십시오 (가장 자주 헤더 파일을 통해). 그러나 모범 사례는 모듈에 데이터를 캡슐화하고 변수에 직접 액세스하는 것이 아니라 함수 또는 메서드를 통해 액세스를 제공하는 것입니다. – nilo
안녕하세요, 저는 많이 검색 한 결과'boost :: shared_memory_object'가 유용하다고 생각했습니다. 하지만 https://theboostcpplibraries.com/boost.interprocess-managed-shared-memory (예제 33.6)에서 간단한 프로그램을 만들려고하면 다음과 같은 오류가 발생합니다. 'boost :: interprocess :: shared_memory_object :: priv_open_or_create (부스트 :: 프로세스 :: ipcdetail :: create_enum_t, char const *, boost :: interprocess :: mode_t, boost :: interprocess :: permissions const &) ':'It' 'shm_open','shm_unlink'에 대한 정의되지 않은 참조를 보여줍니다. –