Меню Закрыть

No cmake cxx compiler could be found

Содержание

Я пытаюсь создать решение Visual Studio с CMake для компиляции последней версии aseprite, и CMake продолжает давать мне:

Я уже скачал GCC, и я использую Visual Studio 2015 .

Я следую этому уроку:

Решение

Эти сообщения об ошибках

просто имейте в виду, что CMake не смог найти ваш компилятор C / CXX для компиляции простой тестовой программы (одна из первых вещей, которые CMake пытается обнаружить при сборке вашей среды сборки).

Действия по поиску вашей проблемы зависят от среды сборки, которую вы хотите сгенерировать. Следующие руководства представляют собой набор ответов здесь о переполнении стека и некоторые из моих собственных опытов с CMake в Microsoft Windows 7/8/10 и Ubuntu 14.04.

Предпосылками

  • Вы установили компилятор / > или же Как мне сказать CMake использовать Clang в Windows?
  • У вас последняя CMake версия
  • У вас есть права доступа к диску, который вы хотите, чтобы CMake генерировал вашу среду сборки
  • У вас есть чистый каталог сборки (потому что CMake выполняет кеширование с последней попытки), например как подкаталог вашего исходного дерева

    Windows cmd.exe

    Баш оболочка

    и убедитесь, что ваша командная оболочка указывает на ваш недавно созданный двоичный каталог вывода.

    Общие вещи, которые вы можете / должны попробовать

    Может ли CMake найти и запустить с любым / вашим компилятором по умолчанию? Беги без генератора

    Идеально, если он правильно определил генератор для использования — как здесь Visual Studio 14 2015

    Что же на самом деле не удалось?

    В выходной директории предыдущей сборки посмотрите на CMakeFilesCMakeError.log для любого сообщения об ошибке, которое имеет смысл для вас, или попробуйте открыть / скомпилировать тестовый проект, сгенерированный в CMakeFiles[Version]CompilerIdC | CompilerIdCXX непосредственно из командной строки (как указано в журнале ошибок).

    CMake не может найти Visual Studio

    Попробуйте выбрать правильный версия генератора :

    Если это не помогает, попробуйте сначала установить переменные среды Visual Studio (путь может отличаться):

    или используйте Developer Command Prompt for VS2015 ярлык в меню Пуск Windows под All Programs / Visual Studio 2015 / Visual Studio Tools (спасибо в @Antwane за подсказку).

    Фон: CMake поддерживает все выпуски и версии Visual Studio (Express, Community, Professional, Premium, Test, Team, Enterprise, Ultimate и т. Д.). Чтобы определить местоположение компилятора, он использует комбинацию поиска в реестре (например, в HKEY_LOCAL_MACHINESOFTWAREMicrosoftVisualStudio[Version];InstallDir ), системные переменные окружения и — если никто из них ничего не придумал — попробуйте вызвать компилятор.

    CMake не может найти GCC (MinGW / MSys)

    Вы начинаете MSys bash оболочка с msys.bat и просто попробуйте позвонить напрямую gcc

    Здесь он нашел gcc и жалуется, что я не дал ему никаких параметров для работы.

    Поэтому должно работать следующее:

    Если GCC не был найден, позвоните export PATH=. чтобы добавить путь к компилятору (см. Как установить переменную среды PATH в скрипте CMake? ) и попробуй еще раз.

    Если это все еще не работает, попробуйте установить CXX путь к компилятору напрямую путем его экспорта (путь может отличаться)

    Для более подробной информации смотрите Как указать новый путь GCC для CMake

    Заметка: При использовании генератора «MinGW Makefiles» вы должны использовать mingw32-make программа распространяется с MinGW

    До сих пор не работает? Это странно. Пожалуйста, убедитесь, что компилятор есть и имеет права на выполнение (см. Также главу «Предварительные условия» выше).

    В противном случае последнее средство CMake — не пытаться выполнять поиск самого компилятора и устанавливать внутренние переменные CMake напрямую

    В качестве альтернативы эти переменные также могут быть установлены через cmake-gui.exe на винде. Увидеть Cmake не может найти компилятор

    Фон: Почти так же, как с Visual Studio. CMake поддерживает все виды GCC. Он ищет переменные окружения (CC, CXX и т. Д.) Или просто пытается вызвать компилятор. Кроме того, он обнаружит любые префиксы (когда кросскомпилируете ) и пытается добавить его ко всем binutils из цепочки компиляторов GNU ( ar , ranlib , strip , ld , nm , objdump , а также objcopy ).

    Другие решения

    Я также испытал эту ошибку при работе с CMake:

    Поле «Предупреждение» в статье библиотеки MSDN Visual C ++ в Visual Studio 2015 дал мне помощь, в которой я нуждался.

    Visual Studio 2015 не поставляется с C ++, установленным по умолчанию. Итак, создание нового проекта C ++ предложит вам загрузить необходимые компоненты C ++.

    Это случилось со мной после того, как я установил Visual Studio 15 2017.

    Компилятор C ++ для Visual Studio 14 2015 не был проблемой. Казалось, проблема с Windows 10 SDK.

    Добавление Windows 10 SDK в Visual Studio 14 2015 решило проблему для меня.

    Смотрите прикрепленный скриншот.

    Я столкнулся с этой проблемой при сборке libgit2-0.23.4. Для меня проблема была в том, что компилятор C ++ & связанные пакеты не были установлены с VS2015, поэтому «C: Program Files (x86) Microsoft Visual Studio 14.0 VC vcvarsall.bat» файл отсутствовал, и Cmake не смог найти компилятор.

    Читайте также:  Как восстановить сайты в яндексе

    Я попытался вручную создать проект C ++ в графическом интерфейсе Visual Studio 2015 (C: Program Files (x86) Microsoft Visual Studio 14.0 Common7 IDE devenv.exe)
    и при создании проекта я получил приглашение загрузить C ++ & связанные пакеты.

    После загрузки необходимых пакетов я увидел vcvarsall.bat & Cmake смог найти компилятор & успешно выполнен со следующим журналом:

    Для меня эта проблема исчезла в Windows, когда я переместил свой проект в более мелкий родительский каталог, то есть в:

    Я думаю, что источником проблемы было то, что MSBuild имеет ограничение длины пути к файлу до 260 символов. Это приводит к тому, что базовый тест компилятора, который выполняет CMake, создает проект под названием CompilerIdCXX.vcxproj потерпеть неудачу с ошибкой:

    C1083: Cannot open source file: ‘CMakeCXXCompilerId.cpp’

    потому что длина пути файла, например,

    C:UsersspencDesktop. MyProjectDirectoryuildCMakeFiles. CMakeCXXCompilerId.cpp

    превышает ограничение MAX_PATH.

    Затем CMake заключает, что компилятора CXX нет.

    У меня были такие же ошибки с CMake. В моем случае я использовал неправильную версию Visual Studio в начальном диалоге CMake, где мы должны выбрать компилятор Visual Studio.

    Затем я изменил его на «Visual Studio 11 2012», и все заработало. (У меня на компьютере установлена ​​версия Visual Studio Ultimate 2012). В общем, попробуйте ввести более старую версию Visual Studio в диалоговом окне начальной настройки CMake.

    Убедитесь, что вы выбрали правильную версию Visual Studio. Это сложнее, чем кажется, потому что Visual Studio 2015 на самом деле является Visual Studio 14, и аналогично Visual Studio 2012 — это Visual Studio 11. Я неправильно выбрал Visual Studio 15, то есть фактически Visual Studio 2017, когда установил 2015.

    Для Ubuntu, пожалуйста, установите следующие вещи:

    I’m trying make a Visual Studio solution with CMake to compile the latest version of aseprite and CMake keeps giving me the:

    I’ve already downloaded GCC, and I’m using Visual Studio 2015.

    I’m following this tutorial:

    19 Answers 19

    Those error messages

    just mean that CMake was unable to find your C/CXX compiler to compile a simple test program (one of the first things CMake tries while detecting your build environment).

    The steps to find your problem are dependent on the build environment you want to generate. The following tutorials are a collection of answers here on Stack Overflow and some of my own experiences with CMake on Microsoft Windows 7/8/10 and Ubuntu 14.04.

    Preconditions

    • You have installed the compiler/IDE and it was able to once compile any other program (directly without CMake)
    • You e.g. may have the IDE, but may not have installed the compiler or supporting framework itself like described in Problems generating solution for VS 2017 with CMake or How do I tell CMake to use Clang on Windows?
  • You have the latest CMake version
  • You have access rights on the drive you want CMake to generate your build environment
  • You have a clean build directory (because CMake does cache things from the last try) e.g. as sub-directory of your source tree

    Windows cmd.exe

    Bash shell

    and make sure your command shell points to your newly created binary output directory.

    General things you can/should try

    Is CMake able find and run with any/your default compiler? Run without giving a generator

    Perfect if it correctly determined the generator to use — like here Visual Studio 14 2015

    What was it that actually failed?

    In the previous build output directory look at CMakeFilesCMakeError.log for any error message that make sense to you or try to open/compile the test project generated at CMakeFiles[Version]CompilerIdC | CompilerIdCXX directly from the command line (as found in the error log).

    CMake can’t find Visual Studio

    Try to select the correct generator version:

    If that doesn’t help, try to set the Visual Studio environment variables first (the path could vary):

    or use the Developer Command Prompt for VS2015 short-cut in your Windows Start Menu under All Programs / Visual Studio 2015 / Visual Studio Tools (thanks at @Antwane for the hint).

    Background: CMake does support all Visual Studio releases and flavors (Express, Community, Professional, Premium, Test, Team, Enterprise, Ultimate, etc.). To determine the location of the compiler it uses a combination of searching the registry (e.g. at HKEY_LOCAL_MACHINESOFTWAREMicrosoftVisualStudio[Version];InstallDir ), system environment variables and — if none of the others did come up with something — plainly try to call the compiler.

    Читайте также:  Яндекс дзен настройка ленты

    CMake can’t find GCC (MinGW/MSys)

    You start the MSys bash shell with msys.bat and just try to directly call gcc

    Here it did find gcc and is complaining that I didn’t gave it any parameters to work with.

    So the following should work:

    If GCC was not found call export PATH=. to add your compilers path (see How to set PATH environment variable in CMake script?) and try again.

    If it’s still not working, try to set the CXX compiler path directly by exporting it (path may vary)

    Note: When using the "MinGW Makefiles" generator you have to use the mingw32-make program distributed with MinGW

    Still not working? That’s weird. Please make sure that the compiler is there and it has executable rights (see also preconditions chapter above).

    Otherwise the last resort of CMake is to not try any compiler search itself and set CMake’s internal variables directly by

    Alternatively those variables can also be set via cmake-gui.exe on Windows. See Cmake cannot find compiler

    Background: Much the same as with Visual Studio. CMake supports all sorts of GCC flavors. It searches the environment variables (CC, CXX, etc.) or simply tries to call the compiler. In addition it will detect any prefixes (when cross-compiling) and tries to add it to all binutils of the GNU compiler toolchain ( ar , ranlib , strip , ld , nm , objdump , and objcopy ).

    This happened to me after I installed Visual Studio 15 2017.

    The C++ compiler for Visual Studio 14 2015 was not the problem. It seemed to be a problem with the Windows 10 SDK.

    Adding the Windows 10 SDKs to Visual Studio 14 2015 solved the problem for me.

    See attached screenshot.

    For Ubuntu, please install the below things:

    I also experienced this error when working with CMake:

    The ‘warning’ box in the MSDN library article Visual C++ in Visual Studio 2015 gave me the help that I needed.

    Visual Studio 2015 doesn’t come with C++ installed by default. So, creating a new C++ project will prompt you to download the necessary C++ components.

    This works for me in Ubuntu 17.10 (Artful Aardvark):

    I ran into this issue while building libgit2-0.23.4. For me the problem was that C++ compiler & related packages were not installed with VS2015, therefore "C:Program Files (x86)Microsoft Visual Studio 14.0VCvcvarsall.bat" file was missing and Cmake wasn’t able to find the compiler.

    I tried manually creating a C++ project in the Visual Studio 2015 GUI (C:Program Files (x86)Microsoft Visual Studio 14.0Common7IDEdevenv.exe) and while creating the project, I got a prompt to download the C++ & related packages.

    After downloading required packages, I could see vcvarsall.bat & Cmake was able to find the compiler & executed successfully with following log:

    For me, this problem went away on Windows when I moved my project to a shallower parent directory, i.e. to:

    I think the source of the problem was that MSBuild has a file path length restriction to 260 characters. This causes the basic compiler test CMake performs to build a project called CompilerIdCXX.vcxproj to fail with the error:

    C1083: Cannot open source file: ‘CMakeCXXCompilerId.cpp’

    because the length of the file’s path e.g.

    C:UsersspencDesktop. MyProjectDirectoryuildCMakeFiles. CMakeCXXCompilerId.cpp

    exceeds the MAX_PATH restriction.

    CMake then concludes there is no CXX compiler.

    I had the same errors with CMake. In my case, I have used the wrong Visual Studio version in the initial CMake dialog where we have to select the Visual Studio compiler.

    Then I changed it to "Visual Studio 11 2012" and things worked. (I have Visual Studio Ultimate 2012 version on my PC). In general, try to input an older version of Visual Studio version in the initial CMake configuration dialog.

    Make sure you have selected the correct version of Visual Studio. This is trickier than it seems because Visual Studio 2015 is actually Visual Studio 14, and similarly Visual Studio 2012 is Visual Studio 11. I had incorrectly selected Visual Studio 15 which is actually Visual Studio 2017, when I had 2015 installed.

    None of the solutions here solves my problem — only when I install Windows Update for universal C runtime.

    Now CMake is working and no more link hangs from Visual Studio.

    You can also make sure you are the sudo user and you have READ/WRITE access on the directory you are working. I had a similar problem on OS X, and I got it fixed just by entering in sudo mode.

    Читайте также:  Hynix 4gb 2rx8 pc3 10600u

    Just in case it helps any one like me in future:

    I have had this issue for 24 hours now, on 3 different 64-bit machines(Win7 , Windows 8.1 VM and WIn 8.1 laptop) — whilst trying to build WebKit with VS 2017.

    The simple issue here is that the VC++ compiler (i.e cl.exe and it’s dependent DLLs) is not visible to CMake. Simple. By making the VC++ folders containing those binaries visible to CMake and your working command prompt(if you’re running Cmake from a command prompt), voila! (In addition to key points raised by others , above)

    Anyway, after all kinds of fixes — as posted on these many forums- I discovered that it was SIMPLY a matter of ensuring that the PATH variable’s contents are not cluttered with multiple Visual Studio BIN paths etc; and instead, points to :

    a) the location of your compiler (i.e. cl.exe for your preferred version of Visual Studio ), which in my case(targeting 64-bit platform, and developing on a 64-bit host) is: C:Program Files (x86)Microsoft Visual Studio2017CommunityVCToolsMSVC14.15.26726inHostx64x64

    b) and in addition, the folder containing a dependent DLL called (which cl.exe is dependent on): api-ms-win-crt-runtime-l1-1-0.dll — which on my machine is:

    C:Program Files (x86)Microsoft Visual Studio2017CommunityCommon7IDERemote Debuggerx64

    These two directories being added to a simplified and CUSTOM System Path variable(working under a Admin priviledged commmand prompt), eliminated my "No CMAKE_C_COMPILER could be found" and "No CMAKE_CXX_COMPILER could be found." errors.

    Comments

    Copy link Quote reply

    OlafvdSpek commented Feb 23, 2017 •

    Just installed 2017 RC on a Windows 8 system. Bootstrap and integration went fine, but no libraries can be build. Building a test project in the IDE works fine.

    This comment has been minimized.

    Copy link Quote reply

    ras0219-msft commented Feb 23, 2017

    I’ll see if I can reproduce this on a VM — in the meantime, could you confirm that you can build a simple CMake project using the copy of CMake inside vcpkg?

    This comment has been minimized.

    Copy link Quote reply

    OlafvdSpek commented Mar 6, 2017

    This comment has been minimized.

    Copy link Quote reply

    ras0219-msft commented Mar 8, 2017 •

    Now that VS2017 RTW is out, could you update your VS 2017 installation and try again?

    This comment has been minimized.

    Copy link Quote reply

    OlafvdSpek commented Mar 9, 2017

    RTW on W7 (not W8): CMakeError.log:

    OpenSSL installed just fine though:
    Package openssl:x86-windows is installed

    This comment has been minimized.

    Copy link Quote reply

    derkestrel commented Mar 19, 2017 •

    I ran into the same problem. OpenSSL worked, but packages depending on zlib fail. I think the "cmake not found" is a red herring.

    Digging deeper into the logs it seems the linking of zlib fails.

    from C:UsersUserSourcesvcpkguildtreeszlibx86-windows-relCMakeFilesCMakeError.log
    Section Link:

    Is this the same for you?

    This comment has been minimized.

    Copy link Quote reply

    OlafvdSpek commented Mar 19, 2017

    No, zlib works fine for me. I’m stuck on

    VS only installs Windows SDK 10 by default.

    This comment has been minimized.

    Copy link Quote reply

    derkestrel commented Mar 19, 2017 •

    This comment has been minimized.

    Copy link Quote reply

    OlafvdSpek commented Mar 19, 2017

    No. It should use the Windows SDK 10.

    This comment has been minimized.

    Copy link Quote reply

    ras0219-msft commented Mar 22, 2017

    Ok, we’ve pushed a change that should fix this issue (selects the win10 sdk). Could you update and try again?

    This comment has been minimized.

    Copy link Quote reply

    OlafvdSpek commented Mar 22, 2017 •

    ./vcpkg install aws-sdk-cpp

    This comment has been minimized.

    Copy link Quote reply

    jbhelm commented Apr 8, 2017

    Just wanted to add I was also getting the erroneous "No CMAKE_C_COMPILER could be found" error when attempting to build zlib. In my case, the error in CMakeError.log was:

    It’s caused by the fact that the file "scriptsuildsystemsmsbuildapplocal.ps1" was considered "blocked" by the OS, which results in PowerShell not being able to execute the script. Selecting Properties in Windows Explorer on the file and checking the "Unblock" (This file came from another computer and might be blocked to help protect this computer) option resolved the issue for me.

    This comment has been minimized.

    Copy link Quote reply

    ras0219-msft commented Apr 9, 2017

    I’ve just pushed eb9b85c which should help with this — we had a few remaining uses of Unrestricted in our sources which would trigger failure due to Mark Of The Web.

    Рекомендуем к прочтению

    Добавить комментарий

    Ваш адрес email не будет опубликован.