Wednesday 26 July 2017

Make Statically Linkedin Binary Options


Eu tenho tentado criar uma versão estática ligada de vips, mas foram incapazes de. É possível criar um comando estático ligado vips A plataforma que estou compilando é Ubuntu 16.04. O comando make Estou executando: Eu não estou configurando para usar python ou imagemagick, (aqueles que não mostram na saída config). O erro que eu estou começando é: Do que eu encontrei, por exemplo aqui: Criar binário ligado estaticamente que usa getaddrinfo é que este é um problema com libnss. Mas na saída ./configure --help não há --enable-static-flag. Mesmo assim eu tentei isso e não corrigir o meu problema. As bibliotecas que eu estou ligando contra (de acordo com a saída de configuração, Ive truncado-lo): Existe uma biblioteca particular que estou ligando contra que está causando o problema Eu tentei como este: E parece funcionar: Ive não testou muito embora, E eu suspeito que não é muito estático. Se você executar ldd no binário vips, por exemplo, você terá uma lista longa. Binários estáticos verdadeiros realmente não existem mais. Por que você quer um binário estático Se o seu para facilitar a distribuição, coisas como flatpack e snappy pode ser melhor. Você também pode classificar-de fazer o seu próprio --- por exemplo, vips vem com um script wrapper simples que pode tornar o binário compartilhado relocatable. Vips usa glib para ajudar a portabilidade, e glib tem um monte de coisas dentro Você poderia tentar fazer o seu próprio glib com algumas coisas removidas, pode ajudar. Eu acho que o binário estático iria funcionar em qualquer instalação 16,04, que é algo, mas provavelmente wouldn39t trabalho em um mínimo linux instalar. OpenWRT tem um pacote libvips e that39s muito mínimo, talvez você poderia adaptar que ndash user894763 Sep 27 às 15: 24I instalou um aplicativo, p. Fdisk. Mas exigia bibliotecas para execução. Estou procurando utilitário / ferramenta que me ajudará a criar um binário estático de binários já instalados. Para que eu possa usá-lo em qualquer lugar. As únicas ferramentas confiáveis ​​que eu encontrei é ErmineLight a partir daqui. Mas este é compartilhar-ware. Existe algum software de código aberto está disponível para o mesmo EDIT fdisk é apenas um exemplo. Eu na maioria das vezes trabalho em LFS, Então, se eu tenho que usar qualquer utilitário, eu preciso seguir os passos como Então só para salvar o tempo, estou procurando uma solução na qual vou fazer um binário estático do debian ou De fedora ou de outro distrbution, tentá-lo em LFS, e se trabalha muito bem ou como por minha exigência, eu irei com código-fonte para a compilação. Perguntou May 2 11 at 18:38 Bem. Isso parece uma idéia muito ruim. Mas, é possível. Como fdisk é open source, basta pegar sua fonte, e olhar para o Makefile. Você deve encontrar uma opção que passará - static para gcc na compilação. Eu não sou um guru de C / C, mas até onde eu sei criando um binário estaticamente vinculado a partir de um binário dinâmico existente não é possível. Se você quiser usá-lo em qualquer lugar, eu recomendo usar uma pequena distribuição de manutenção que começa em segundos e permite que você modifique tudo. Faz mais sentido para mim, porque você provavelmente vai querer modificar o disco executando a sua instalação Linux / UNIX. O link funciona para mim. A página tem o número de erros ortográficos / editoriais que você poderia esperar do trabalho de um programador profissional mais do que você esperaria de um site profissional, menos do que você esperaria de um e-mail de phishing. Sobre o mesmo que o post acima, venha a pensar nisso. Parece suspeito que este novo usuário iria se juntar Stack Exchange apenas a tempo de postar um link para o que parece ser um novo site. Ndash G-Man Aug 27 15 at 22: 58configure - Configurar a árvore de origem O script configure configura a árvore de origem para compilar e instalar o Servidor HTTP Apache em sua plataforma específica. Várias opções permitem a compilação de um servidor correspondente às suas necessidades pessoais. Este script, incluído no diretório raiz da distribuição de origem, é para compilação somente em sistemas Unix e Unix. Para outras plataformas, consulte a documentação da plataforma. Consulte também Você deve chamar o script de configuração de dentro do diretório raiz da distribuição. ./configure OPÇÃO. VAR VALUE. Para atribuir variáveis ​​de ambiente (por exemplo, CC. CFLAGS.), Especifique-as como VAR VALUE. Veja abaixo as descrições de algumas das variáveis ​​úteis. As opções a seguir influenciam o comportamento do próprio configure. - C --config-cache Este é um alias para --cache-fileconfig. cache --cache-file FILE Os resultados do teste serão armazenados em cache no arquivo FILE. Esta opção está desativada por padrão. - h --help shortrecursive Saída a ajuda e sair. Com o argumento short, somente as opções específicas para este pacote serão exibidas. O argumento recursivo exibe a ajuda curta de todos os pacotes incluídos. - n --no-create O script de configuração é executado normalmente, mas não cria arquivos de saída. Isso é útil para verificar os resultados do teste antes de gerar makefiles para compilação. - q --quiet Não imprime a verificação. Durante o processo de configuração. --srcdir DIR Define o diretório DIR como o diretório do arquivo de origem. Padrão é o diretório onde o configure está localizado, ou o diretório pai. --silent Igual a --quiet - V --version Exibe as informações de copyright e sai. Essas opções definem o diretório de instalação. A árvore de instalação depende do layout selecionado. --prefix PREFIX Instale arquivos independentes da arquitetura em PREFIX. Por padrão, o diretório de instalação é definido como / usr / local / apache2. --exec-prefix EPREFIX Instale arquivos dependentes da arquitetura em EPREFIX. Por padrão, o diretório de instalação é definido para o diretório PREFIX. Por padrão, make install instalará todos os arquivos em / usr / local / apache2 / bin. / Usr / local / apache2 / lib etc. Você pode especificar um prefixo de instalação diferente de / usr / local / apache2 usando --prefix. Por exemplo --prefixHOME. --enable-layout LAYOUT Configure o código-fonte e crie scripts para assumir uma árvore de instalação baseada no layout LAYOUT. Isso permite que você especifique separadamente os locais para cada tipo de arquivo dentro da instalação do Apache HTTP Server. O arquivo config. layout contém várias configurações de exemplo e você também pode criar sua própria configuração personalizada seguindo os exemplos. Os diferentes layouts neste arquivo são agrupados em ltLayout FOOgt. Lt / Layoutgt e referidos por nome como em FOO. O layout padrão é o Apache. Para um melhor controle dos diretórios de instalação, use as opções abaixo. Observe que os padrões de diretório são definidos pelo autoconf e são substituídos pela configuração de layout correspondente. --bindir DIR Instalar executáveis ​​do usuário no DIR. Os executáveis ​​do usuário estão suportando programas como htpasswd. Dbmmanage. Etc, que são úteis para os administradores do site. Por padrão DIR é definido como EPREFIX / bin. --datadir DIR Instale dados independentes da arquitetura somente leitura no DIR. Por padrão datadir é definido como PREFIX / share. Esta opção é oferecida pelo autoconf e atualmente não é utilizada. --includedir DIR Instale os arquivos de cabeçalho C no diretório. Por padrão, includedir é definido como EPREFIX / include. --infodir DIR Instalar a documentação de informações no DIR. Por padrão, infodir é definido como PREFIX / info. Esta opção está actualmente não utilizada. --libdir DIR Instalar bibliotecas de código objeto em DIR. Por padrão libdir é definido como EPREFIX / lib. --libexecdir DIR Instale os executáveis ​​do programa (ou seja, módulos compartilhados) no DIR. Por padrão libexecdir é definido como EPREFIX / modules. --localstatedir DIR Instalar dados modificáveis ​​de máquina única no DIR. Por padrão localstatedir é definido como PREFIX / var. Esta opção é oferecida pelo autoconf e atualmente não é utilizada. --mandir DIR Instale a documentação man no diretório. Por predefinição, mandir é definido como EPREFIX / man. --oldincludedir DIR Instale arquivos de cabeçalho C para non-gcc no DIR. Por padrão oldincludedir é definido como / usr / include. Esta opção é oferecida pelo autoconf e atualmente não é utilizada. --sbindir DIR Instale os executáveis ​​do administrador do sistema no DIR. Esses são programas de servidor como o httpd. Apachectl. Suexec. Etc, que são necessários para executar o Apache HTTP Server. Por padrão, sbindir é definido como EPREFIX / sbin. --sharedstatedir DIR Instalar dados modificáveis ​​independentes da arquitetura no DIR. Por padrão, sharedstatedir é definido como PREFIX / com. Esta opção é oferecida pelo autoconf e atualmente não é utilizada. --sysconfdir DIR Instale dados de máquina única de leitura como os arquivos de configuração do servidor httpd. conf. Mime. types. Etc em DIR. Por padrão sysconfdir é definido como PREFIX / conf. Essas opções são usadas para compilar o Servidor HTTP Apache para executar em outro sistema. Em casos normais, ao criar e executar o servidor no mesmo sistema, essas opções não são usadas. --build BUILD Define o tipo de sistema do sistema no qual as ferramentas estão sendo construídas. O padrão é o resultado do script config. guess. --host HOST Define o tipo de sistema do sistema no qual o servidor será executado. HOST padrão é BUILD. --target TARGET Configurar para construir compiladores para o tipo de sistema TARGET. O padrão é HOST. Esta opção é oferecida pelo autoconf e não é necessária para o Apache HTTP Server. Essas opções são usadas para ajustar os recursos que o servidor HTTP terá. Geralmente, você pode usar a seguinte sintaxe para ativar ou desativar um recurso: --disable - FEATURE Não incluir FEATURE. Este é o mesmo que --enable - FEATURE no. --enable - FEATURE ARG Incluir FEATURE. O valor padrão para ARG é sim. --enable - MODULE shared O módulo correspondente será construído como módulo DSO. Por padrão habilitado módulos são vinculados dinamicamente. --enable - MODULE static O módulo correspondente será ligado estaticamente. Note configure não reclamará sobre --enable - foo mesmo se foo não existir, então você precisa digitar com cuidado. A maioria dos módulos são compilados por padrão e precisam ser desativados explicitamente ou usando a palavra-chave poucos (veja - enable-modules. --enable-mods-shared e - enable-mods-static abaixo para mais explicações) ou --enable - módulos não devem ser removidos como um grupo. Outros módulos não são compilados por padrão e precisam ser ativados explicitamente ou usando as palavras-chave all ou reallyall para estar disponível. Para descobrir quais módulos são compilados por padrão, execute ./configure - h ou ./configure --help e procure Recursos Opcionais. Suponha que você esteja interessado em modexample1 e modexample2. E você vê isso: Então modexample1 é habilitado por padrão, e você usaria --disable-example1 para não compilá-lo. Modexample2 está desativado por padrão e você usaria --enable-example2 para compilá-lo. Módulos de multiprocessamento. Ou MPMs, implementar o comportamento básico do servidor. Um único MPM deve estar ativo para que o servidor funcione. A lista de MPMs disponíveis aparece na página de índice do módulo. Os MPMs podem ser construídos como DSOs para carregamento dinâmico ou estaticamente vinculados ao servidor e são habilitados usando as seguintes opções: Escolha o MPM padrão para o servidor. Se MPMs são construídos como módulos DSO (consulte --enable-mpms-shared), esta diretiva seleciona o MPM que será carregado no arquivo de configuração padrão. Caso contrário, esta diretiva seleciona o único MPM disponível, que será vinculado estaticamente ao servidor. Se esta opção for omitida, o MPM padrão para seu sistema operacional será usado. Habilite uma lista de MPMs como módulos compartilhados dinâmicos. Um desses módulos deve ser carregado dinamicamente usando a diretiva LoadModule. MPM-LIST é uma lista separada por espaços de nomes MPM entre aspas. Por exemplo: Além disso, você pode usar a palavra-chave especial all. Que irá selecionar todos os MPMs que suportam o carregamento dinâmico na plataforma atual e construí-los como módulos DSO. Por exemplo: Para adicionar outros módulos de terceiros, use as seguintes opções: --with-module module-type. Módulo-arquivo, módulo-tipo. Module-file Adicione um ou mais módulos de terceiros à lista de módulos ligados estaticamente. O arquivo-módulo do módulo file-module será pesquisado no subdiretório modules / module-type de sua árvore de origem do servidor Apache HTTP. Se ele não for encontrado, configure considera módulo-file para ser um caminho de arquivo absoluto e tenta copiar o arquivo de origem para o subdiretório de tipo de módulo. Se o subdiretório não existir, ele será criado e preenchido com um Makefile. in padrão. Esta opção é útil para adicionar pequenos módulos externos consistindo em um arquivo de origem. Para módulos mais complexos, você deve ler a documentação do fornecedor. Observação Se você quiser criar um módulo DSO em vez de um apontar estaticamente vinculado usar apxs. --enable-maintainer-mode Ative os avisos de depuração e de tempo de compilação e carregue todos os módulos compilados. --enable-mods-shared MODULE-LIST Define uma lista de módulos a serem habilitados e criados como módulos compartilhados dinâmicos. Isso significa que esses módulos precisam ser carregados dinamicamente usando a diretiva LoadModule. MODULE-LIST é uma lista separada por espaços de modulenames entre aspas. Os nomes dos módulos são fornecidos sem o mod anterior. Por exemplo: --enable-mods-sharedheaders rewrite dav Além disso, você pode usar as palavras-chave especiais reallyall. todos. Mais e poucos. Por exemplo, compilar a maioria dos módulos e compilá-los como módulos DSO, só compilará um conjunto muito básico de módulos. O conjunto padrão é mais. As diretivas LoadModule para os módulos escolhidos serão geradas automaticamente no arquivo de configuração principal. Por padrão, todas essas diretivas serão comentadas, exceto para os módulos que são obrigatórios ou explicitamente selecionados por um argumento configure - enable-foo. Você pode alterar o conjunto de módulos carregados ativando ou desativando as diretivas LoadModule no httpd. conf. Além disso, as diretivas LoadModule para todos os módulos construídos podem ser ativadas através da opção de configuração --enable-load-all-modules. --enable-mods-static MODULE-LIST Esta opção comporta-se como --enable-mods-shared. Mas irá ligar os módulos dados estaticamente. Isso significa que esses módulos estarão sempre presentes durante a execução do httpd. Eles não precisam ser carregados com LoadModule. --enable-modules MODULE-LIST Esta opção se comporta como --enable-mods-shared. E também ligará os módulos dados dinamicamente. A palavra-chave especial none desativa a compilação de todos os módulos. --enable-v4-mapped Permitir que os soquetes IPv6 gerenciem conexões IPv4. --with-port PORT Define a porta na qual o httpd irá ouvir. Esse número de porta é usado ao gerar o arquivo de configuração httpd. conf. O padrão é 80. --with-program-name Define um nome alternativo executável. O padrão é httpd. Essas opções são usadas para definir pacotes opcionais. Geralmente, você pode usar a seguinte sintaxe para definir um pacote opcional: --with - PACKAGE ARG Use o pacote PACKAGE. O valor padrão para ARG é sim. --without - PACKAGE Não use o pacote PACKAGE. Este é o mesmo que --with - PACKAGE no. Esta opção é fornecida pelo autoconf, mas não é muito útil para o Apache HTTP Server. --with-apr DIR FILE O Apache Portable Runtime (APR) faz parte da distribuição de fonte httpd e será automaticamente construído em conjunto com o servidor HTTP. Se você quiser usar um APR já instalado em vez disso, você tem que dizer configurar o caminho para o script apr-config. Você pode definir o caminho absoluto eo nome ou o diretório para o APR instalado. Apr-config deve existir dentro deste diretório ou do subdiretório bin. --with-apr-util DIR ARQUIVO Os Apache Portable Runtime Utilities (APU) fazem parte da distribuição de fonte httpd e serão automaticamente compilados em conjunto com o servidor HTTP. Se você quiser usar uma APU já instalada em vez disso, você tem que dizer configurar o caminho para o script apu-config. Você pode definir o caminho absoluto eo nome ou o diretório para a APU instalada. Apu-config deve existir dentro deste diretório ou do subdiretório bin. --with-ssl DIR Se modssl foi habilitado configure procura um OpenSSL instalado. Você pode definir o caminho do diretório para o SSL / TLS toolkit em vez disso. --with-z DIR configura pesquisas automaticamente para uma biblioteca zlib instalada se sua configuração de origem requer uma (por exemplo, quando moddeflate estiver habilitado). Você pode definir o caminho do diretório para a biblioteca de compactação em vez disso. Vários recursos do Servidor HTTP Apache, incluindo modauthndbm e modrewrite s DBM RewriteMap usam bancos de dados de chave / valor simples para pesquisas rápidas de informações. SDBM está incluído no APU, portanto, esse banco de dados está sempre disponível. Se você quiser usar outros tipos de banco de dados, use as seguintes opções para ativá-los: --with-gdbm path Se nenhum caminho for especificado, configure irá procurar os arquivos de inclusão e as bibliotecas de uma instalação do GNU DBM nos caminhos usuais de busca. Um caminho explícito fará com que o configure procure em path / lib e path / include para os arquivos relevantes. Finalmente, o caminho pode especificar caminhos de inclusão e biblioteca específicos separados por dois pontos. --with-ndbm path Como --with-gdbm. Mas procura por uma nova instalação DBM. --com-berkeley-db caminho Como --with-gdbm. Mas procura uma instalação de Berkeley DB. Observação As opções de DBM são fornecidas pela APU e passadas para seu script de configuração. Eles são inúteis ao usar uma APU já instalada definida por --with-apr-util. Você pode usar mais do que uma implementação do DBM em conjunto com seu servidor HTTP. O tipo DBM apropriado será configurado dentro da configuração de tempo de execução a cada momento. --enable-static-support Criar uma versão estaticamente vinculada dos binários de suporte. Isso significa que um executável autônomo será construído com todas as bibliotecas necessárias integradas. Caso contrário, os binários de suporte são vinculados dinamicamente por padrão. --enable-suexec Use esta opção para ativar o suexec. Que permite que você defina uid e gid para processos gerados. Não use essa opção a menos que você entenda todas as implicações de segurança de executar um binário suid em seu servidor. Outras opções para configurar o suexec são descritas abaixo. É possível criar um binário ligado estáticamente de um único programa de suporte utilizando as seguintes opções: --enable-static-ab Construir uma versão estática ligada de ab. --enable-static-checkgid Construir uma versão estaticamente vinculada do check-in. --enable-static-htdbm Criar uma versão estaticamente vinculada do htdbm. --enable-static-htdigest Criar uma versão estaticamente vinculada do htdigest. --enable-static-htpasswd Construa uma versão estaticamente vinculada do htpasswd. --enable-static-logresolve Criar uma versão ligada estática do logresolve. --enable-static-rotatelogs Construir uma versão estaticamente vinculada de rotatelogs. As opções a seguir são usadas para ajustar o comportamento do suexec. Consulte Configuração e instalação do suEXEC para obter mais informações. --with-suexec-bin Define o caminho para o binário suexec. O padrão é --sbindir (consulte Ajuste fino dos diretórios de instalação). --with-suexec-caller Define o usuário autorizado a chamar suexec. Ele deve ser o mesmo que o usuário sob o qual o httpd normalmente é executado. --with-suexec-docroot Define a árvore de diretórios sob a qual o acesso do suexec é permitido para executáveis. O valor padrão é --datadir / htdocs. --with-suexec-gidmin Defina isso como o GID mais baixo permitido para ser um usuário de destino para o suexec. O valor padrão é 100. --with-suexec-logfile Define o nome do arquivo de log do suexec. Por padrão, o logfile chama-se suexeclog e está localizado em --logfiledir. --with-suexec-safepath Define o valor da variável de ambiente PATH a ser definida para processos iniciados pelo suexec. O valor padrão é / usr / local / bin: / usr / bin: / bin. --with-suexec-userdir Isso define o subdiretório no diretório de usuários que contém todos os executáveis ​​para os quais o acesso do suexec é permitido. Essa configuração é necessária quando você deseja usar o suexec juntamente com diretórios específicos do usuário (conforme fornecido por moduserdir). O padrão é publichtml. --with-suexec-uidmin Defina isso como o UID mais baixo permitido para ser um usuário de destino para suexec. O valor padrão é 100. --with-suexec-umask Define umask para processos iniciados pelo suexec. O padrão é as configurações do sistema. Existem algumas variáveis ​​de ambiente úteis para substituir as opções feitas pelo configure ou para ajudá-lo a encontrar bibliotecas e programas com nomes ou locais não padrão. CC Define o comando do compilador C a ser usado para a compilação. CFLAGS Define as bandeiras do compilador C que você deseja usar para compilação. CPP Define o comando do pré-processador C a ser utilizado. CPPFLAGS Definir sinalizadores de pré-processador C / C, p. - Incluído se você tiver cabeçalhos em um diretório não-padrão incluído. LDFLAGS Definir bandeiras de ligação, p. - L libdir se você tem bibliotecas em um diretório não padronizado libdir. Aviso: Esta não é uma seção QampA. Os comentários colocados aqui devem ser apontados para sugestões sobre como melhorar a documentação ou o servidor e podem ser removidos novamente pelos nossos moderadores se forem implementados ou considerados inválidos / fora do tópico. Perguntas sobre como gerenciar o Servidor HTTP Apache devem ser direcionadas para nosso canal IRC, httpd, no Freenode, ou enviadas para nossas listas de discussão. Copyright 2016 A Apache Software Foundation. Licenciado sob a Licença Apache, Versão 2.0.CMake FAQ Informações gerais e disponibilidade O que é o CMake O CMake é um sistema multiplataforma de código aberto. O CMake é usado para controlar o processo de compilação do software usando arquivos de configuração independentes de plataforma e compiladores independentes. O CMake gera makefiles e espaços de trabalho nativos que podem ser usados ​​no ambiente do compilador de sua escolha. O CMake é bastante sofisticado: é possível suportar ambientes complexos que requerem configuração do sistema, geração de pré-processador, geração de código e instanciação de modelos. Acesse www. cmake. org/overview para saber mais sobre o CMake. O que é a versão atual A versão mais recente do CMake está sempre disponível em: www. cmake. org/download A partir daí, você pode buscar CMake binários para Windows ou várias variantes Unix, ou você pode baixar o código fonte do CMake. Você também pode acessar o desenvolvimento noturno através do Git, consulte www. cmake. org/download para obter mais informações. Você também pode navegar no repositório git on-line. Encontrei um bug O que devo fazer Se você tiver um patch para contribuir, leia CONTRIBUTING. rst na parte superior da árvore de fontes do CMake. Caso contrário, informe o bug no nosso rastreador de bug: www. cmake. org/Bug Por favor, certifique-se de olhar para os bugs antigos para não incluir duplicatas, incluir instruções detalhadas do bug e como reproduzi-lo. Quero um novo recurso no CMake. O que devo fazer Relate uma solicitação de recurso no nosso rastreador de bugs www. cmake. org/Bug Por favor, certifique-se de olhar para as solicitações de recurso antigo para não incluir duplicatas, incluir instruções detalhadas do recurso e implementação proposta. Qual é a versão mais recente coberta pelo Mastering CMake livro Uma nova edição do Mastering CMake livro foi lançado que documentos CMake 2.6. Os seguintes recursos foram adicionados desde a impressão do livro: Novo comando INSTALL (cmake --help-command INSTALL) Novo comando LIST (cmake --help-command LIST) Os comandos FINDPATH, FINDPROGRAM e FINDFILE atualizados são mais poderosos (cmake - - help-command FINDPATH) Suporte a instalação de RPATH e Mac OS X (cmake --help-command SETTARGETPROPERTIES) CPack Beta (não terminado ou documentado) EXECUTEPROCESS foi adicionado e substitui EXECPROGRAM Outras mudanças foram correções de bugs e reestruturação CMake interna Onde posso encontrar Pesquisável CMake Mailing Arquivos Existem pelo menos estes: Executando CMake Existe uma opção para produzir compilação mais detalhada Em geradores Makefile, você pode definir a variável Makefile VERBOSE como 1. Por exemplo, em UNIX: Você também pode definir CMAKEVERBOSEMAKEFILE como ON. No Windows (nmake) você pode substituir CMAKEVERBOSEMAKEFILE usando On Unix fazer você pode sobretudo substituir o modo detalhado usando Se você estiver no Windows usando Borland ou NMake Makefiles, você verá linhas como: A razão para isso é que Borland e Microsoft Visual Studio Fazer programas têm limitação no comprimento de cadeias de comandos. Eles superam esta limitação, escrevendo argumentos para o arquivo e, em seguida, passar arquivo para o programa. Se você realmente deseja ver o que o comando parece, defina CMAKESTARTTEMPFILE e CMAKEENDTEMPFILE para - ser avisado, no entanto, você não pode defini-las como variáveis ​​na linha de comando CMake com - D. Em vez disso, veja a parte inferior do arquivo Modules / Platform / Windows. cmake e descomente as linhas que definem essas variáveis ​​para a seqüência vazia. Existe uma maneira de ignorar a verificação de bibliotecas dependentes durante a compilação Usando o Gerador Makefile Ao usar o gerador Makefile sob nix você pode anexar / rapidamente ao seu nome alvo. Por exemplo: No Windows, use uma barra invertida em vez disso: Usando o Visual Studio gt 7.1 Se você tiver o Visual Studio 7.1 ou superior, poderá usar a opção nativa para clicar com o botão direito do mouse em um projeto e optar por criar apenas esse projeto. Usando o Visual Studio lt 7.0 O CMake não tenta compilar todas as bibliotecas dependentes quando compila uma biblioteca, mas o fará para alvos binários. Você não pode evitar isso, no entanto, você pode tirar proveito de CTRLF7 para compilar manualmente um arquivo de origem para o alvo afetado e, em seguida, relink o alvo clicando com o botão direito sobre ele e escolhendo Link. Youll tem que garantir que todas as bibliotecas dependentes são feitas up-to-date no entanto ou sofrer através Visuals lento verificar. Eu definir uma variável cmake no meu ambiente, mas não mudou nada. Por que as configurações de compilação do CMake são armazenadas no cache do CMake correspondente a uma árvore de construção de projetos. Eles são chamados de entradas do cache CMake e não têm relação com as variáveis ​​de ambiente de shell de comando. Use uma GUI do CMake (CMakeSetup no Windows ou ccmake no UNIX) ou o modo do assistente (cmake - i) para editar as entradas do cache. Valores iniciais também podem ser especificados para uma compilação usando o argumento de linha de comando - D para cmake quando é executado pela primeira vez para produzir uma nova árvore de compilação. Como usar um compilador diferente Método 1: usar variáveis ​​de ambiente Para C e C, defina as variáveis ​​de ambiente CC e CXX. Este método não é garantido para trabalhar para todos os geradores. (Especificamente, se você estiver tentando definir Xcodes GCCVERSION. Este método confunde Xcode.) Método 2: use cmake - D Definir a apropriada CMAKEFOOCOMPILER variável (s) para um válido compilador nome ou caminho completo na linha de comando usando cmake - D . Método 3 (evitar): use set () Defina a variável apropriada CMAKEFOOCOMPILER para um nome de compilador válido ou caminho completo em um arquivo de lista usando set (). Isso deve ser feito antes que qualquer idioma seja definido (ou seja, antes de qualquer comando project () ou enablelanguage ()). Eu mudo CMAKECCOMPILER na GUI, mas ele muda de volta na próxima etapa de configuração. Por que, uma vez que uma árvore de compilação é criada com um determinado compilador não pode ser alterada. Há uma variedade de razões de implementação dessa política. No CCMake, digitar caminhos completos é tedioso. Há uma maneira melhor Desde CMake 1.6, você pode usar a conclusão de guia nas entradas de caminho em CCMake. Tudo o que você faz é digitar o primeiro par de caracteres e pressione a tecla ltTABgt. O CCMake examinará o caminho digitado atual e tentará expandi-lo para algum caminho existente. Se isso for possível, ele o fará. Se não, não vai fazer nada. Árvores de compilação fora da fonte O que é uma compilação fora da fonte Quando sua compilação gera arquivos, eles precisam ir para algum lugar. Uma compilação na fonte os coloca na árvore de origem. Uma compilação fora da fonte os coloca em um diretório completamente separado, para que sua árvore de origem não seja alterada. No primeiro exemplo, uma compilação no local é executada, ou seja, os binários são colocados no mesmo diretório que o código-fonte. No segundo exemplo, uma compilação fora de lugar é executada, ou seja, o código-fonte, bibliotecas e executáveis ​​são produzidos em um diretório separado do (s) diretório (s) de código-fonte. São recomendadas compilações fora da fonte, pois você pode criar múltiplas variantes em diretórios separados, p. HelloBuildDebug, HelloBuildRelease. Observação: antes de executar uma compilação fora da fonte, certifique-se de que todas as informações de compilação geradas no CMake sejam removidas do diretório de origem, p. Diretório CMakeFiles, CMakeCache. txt. Eu executar uma compilação fora de fonte, mas CMake gera na fonte de qualquer maneira. Por que Isso significa que há um arquivo CMakeCache. txt na árvore de origem, possivelmente como parte de uma compilação existente na fonte. Se CMake é dado o caminho para um diretório com um arquivo CMakeCache. txt, ele assume o diretório é uma árvore de compilação. Portanto, se um executa cmake. / Mysrc para construir fora-de-fonte, mas há um arquivo mysrc / CMakeCache. txt então cmake irá tratar mysrc como a árvore de compilação. Este é um efeito colateral do recurso que permite cmake. Para ser usado para regenerar uma árvore de compilação. O comportamento não será alterado porque misturar compilações in-source e out-of-source não é seguro de qualquer maneira (cabeçalhos configurados podem ser encontrados no lugar errado). Por que o CMake usa caminhos completos ou posso copiar minha árvore de compilação O CMake usa caminhos completos porque: os arquivos de cabeçalho configurados podem ter caminhos completos neles, e mover esses arquivos sem a reconfiguração causaria um comportamento upredictable. Porque o cmake suporta fora das compilações de origem, se os comandos personalizados usassem caminhos relativos para a árvore de origem, eles não funcionariam quando são executados na árvore de compilação porque o diretório atual estaria incorreto. Em sistemas Unix rpaths pode ser construído em executáveis ​​para que eles possam encontrar bibliotecas compartilhadas em tempo de execução. Se a árvore de compilação é movida, os executáveis ​​antigos podem usar as bibliotecas compartilhadas antigas e não as novas. Pode a árvore de compilação ser copiada ou movida A resposta curta é NÃO. A razão é porque caminhos completos são usados ​​no CMake, veja acima. O principal problema é que cmake precisaria detectar quando a árvore binária foi movida e executada novamente. Muitas vezes, quando as pessoas querem mover uma árvore binária é para que eles possam distribuí-lo para outros usuários que não podem ter cmake em que caso isso não iria funcionar, mesmo se cmake iria detectar o movimento. A solução é criar uma nova árvore de compilação sem copiar ou mover a antiga. O CMake não gera um destino make distclean. Por que Algumas árvores de compilação criadas com GNU autotools têm um make distclean target que limpa a build e também remove Makefiles e outras partes do sistema de compilação gerado. CMake não gera um make distclean alvo porque CMakeLists. txt arquivos podem executar scripts e comandos arbitrários CMake não tem nenhuma maneira de rastrear exatamente quais arquivos são gerados como parte da execução CMake. Fornecer um alvo distclean daria aos usuários a falsa impressão de que ele iria funcionar como esperado. (CMake gera um make clean target para remover arquivos gerados pelo compilador e linker.) Um make distclean target só é necessário se o usuário executar uma compilação in-source. O CMake suporta compilações in-source, mas nós incentivamos fortemente os usuários a adotar a noção de uma compilação fora da fonte. Usar uma árvore de compilação que é separada da árvore de origem impedirá CMake de gerar quaisquer arquivos na árvore de origem. Como o CMake não altera a árvore de origem, não há necessidade de um destino distclean. É possível iniciar uma compilação nova excluindo a árvore de compilação ou criando uma árvore de compilação separada. (Se um CMakeLists. txt usa ADDCUSTOMCOMMAND para gerar arquivos de origem na árvore de origem, não a árvore de compilação, em seguida, em CMake 2.2 ou superior make clean irá removê-los.) A execução make clean não remove as saídas de comandos personalizados. Por que no CMake 2.2 e superiores saídas de comandos personalizados devem ser removidos por make clean. Verifique se você está usando pelo menos esta versão. Antes do CMake 2.2, as saídas de comandos personalizadas não foram automaticamente adicionadas à lista de arquivos a serem limpos. No CMake 2.0, o desenvolvedor pode especificar uma lista de arquivos a serem excluídos. Isso pode ser feito usando SETDIRECTORYPROPERTIES configuração propriedade ADDITIONALMAKECLEANFILES para a lista de arquivos. No entanto, recomendamos fortemente usar uma compilação fora da fonte que nunca grava nenhum arquivo na árvore de origem. A utilização de uma árvore de origem e de compilação reduz muito a necessidade de limpar e tornar os alvos distclean limpar ficheiros que diferem entre compilações. Escrevendo CMakeLists. txt Como ter compatibilidade para trás e para frente Como CMake 2.6 nós empregamos um mecanismo de Política para fornecer compatibilidade para trás. O requisito básico para projetos é incluir uma linha na parte superior do arquivo CMakeLists. txt mais alto: Isso informa versões do CMake anteriores ao especificado que eles são muito antigos para criar o projeto. Eles irão relatar essas informações ao usuário. Ele também informa versões do CMake mais recente do que o especificado que o projeto pode não estar ciente de políticas introduzidas em versões posteriores, que permite compatibilidade adicional. Para obter mais documentação, consulte Como obter a fonte atual ou o diretório binário A variável CMAKECURRENTSOURCEDIR contém o caminho absoluto para seu diretório de origem atual, enquanto CMAKECURRENTBINARYDIR aponta para o diretório binário equivalente. Por que minhas variáveis ​​CMake não são atualizadas na GUI após um comando SET As variáveis ​​de cache listadas na GUI ao pressionar Configurar são usadas para inicializar os valores vistos pelo código nos arquivos CMakeLists. txt. As alterações feitas pelo código são usadas durante a etapa de configuração e vistas pelos geradores, mas não são armazenadas de volta no cache. Por exemplo: ativará a criação de bibliotecas compartilhadas para o diretório que contém o comando e todos os subdiretórios, mas a alteração não aparecerá na GUI. Você pode usar as opções CACHE e FORCE no comando SET para alterar variáveis ​​de uma forma que será refletida na GUI. Execute para ver instruções completas para o comando. Como posso alterar o modo de compilação padrão e vê-lo refletido na GUI Adapte os seguintes comandos no CMakeLists. txt (este exemplo define o modo Release With Debug Information): Como gerar um executável e usar o executável para gerar um file Create the generator executable by just adding a target: The rest of the process is simpler in CMake 2.6 and above than in previous versions. Use ADDCUSTOMCOMMAND to specify a custom build rule for the file. (In this example we assume generate accepts the input and output files as arguments.) This tells CMake how to build the file but does not actually add a rule to the build system. Another target must require it. One may create a custom target explicitly for this rule: or the file may be added as part of some other target: In CMake 2.4 and below the generate target may not be specified directly in the COMMAND option of addcustomcommand (but it can still be used in the DEPENDS option as of CMake 2.4). Instead use GETTARGETPROPERTY to obtain the location of the generated executable. Additionally, the output must always be specified by full path. How can I generate a source file during the build The ADDCUSTOMCOMMAND command lets you generate a source file that you can then include in another target. For example: This will create an executable by copying bar. c to foo. c and then compiling foo. c to produce foo. CMake allows you to put generated source files in the current source or binary directory, so we were careful to output foo. c to the current binary directory. When we add foo. c to foo, CMake will look in either directory for it. Even if foo. c does not yet exist, CMake is smart enough to notice that a custom command creates it. (For the file named as the OUTPUT, CMake has its GENERATED source file property set to true.) Sometimes, the program doing the generation may generate multiple output files that each need to be part of the build. CMake 2.4 or higher supports having multiple files listed in the OUTPUT section. For example, suppose you had a program that read input. txt and generated three files output1.cpp, output2.h, and output3.cpp, and that those three files needed to be compiled into an executable program. The cmake list file for that would look like this: CMake 2.4 allows you to generate a header file. Because generated headers often cause unnecessary rebuilds, you should try to avoid them consider using the CONFIGUREFILE command to prepare the header at CMake time. If you must generate a header file, use code like this: This is like the first example above, except that it generates a header instead of a C file. The header might not exist when the build system scans foo. cs dependencies, so there is no way for CMake to know that this target requires foo. h unless we can tell it that foo. h may exist in the future. We give CMake this knowledge by listing the generated header file in the set of source files for the target. (This requires CMake 2.4. Previous versions of CMake required use of the OBJECTDEPENDS source file property.) How can I add a dependency to a source file which is generated in a subdirectory Rules created with ADDCUSTOMCOMMAND as above have scope only in the directory in which they are specified. If the generated file is needed in another directory, a target-level dependency needs to be added. Create a target in the subdirectory with the custom rule in order to drive it: Now other targets can depend on the target from the subdirectory: How can I generate a file used in more than one target in the same directory CMake will generate a copy of a custom command in the build rules for every target that lists the custom command output as a source file. There is no other place to put it. If a single custom command output is listed in more than one target and the targets have no dependency relationship they will race to run the custom command during a parallel build and possibly clobber each other. For example: There are at least two solutions to this problem. First, one may use adddependencies to serialize the targets involved: Second, one may add a custom target dedicated to generating files for the other targets: The latter solution ensures that generated files are up to date before any of the independent targets build so none of them will run the custom command and there will be no race. I use EXECPROGRAM but the result is not set in subdirectories. Why An unfortunate holdover from ancient CMake versions is that certain commands are inherited into subdirectories and others are not. EXECPROGRAM is not inherited. What this means is that when the listfile code from a parent directory executes in a subdirectory the EXECPROGRAM command is left out. Therefore the code executes differently. This problem was fixed in CMake 2.2, but for older versions you will have to cache the result: This will store the result in a global location so it will be available in the subdirectory. Be sure to choose a descriptive name for MYOUTPUT to avoid conflict in the global setting. How can I get or set environment variables CMake names environment variables using an ENV prefix and surrounding the names in curly braces. Here is an example: Reading variables will work in any version of CMake. Writing to them works in CMake 2.2 and higher using the following syntax: Note that there is currently no way to tell apart an empty environment variable value from a variable that is not set at all. One should avoid using environment variables for controlling the flow of CMake code (such as in IF commands). The build system generated by CMake may re-run CMake automatically when CMakeLists. txt files change. The environment in which this is executed is controlled by the build system and may not match that in which CMake was originally run. If you want to control build settings on the CMake command line, you need to use cache variables set with the - D option. The settings will be saved in CMakeCache. txt so that they dont have to be repeated every time CMake is run on the same build tree. Also, environment variables SET in the CMakeLists. txt only take effect for cmake itself ( configure-time ), so you cannot use this method to set an environment variable that a custom command might need ( build-time ). Barring environment variable support by various CMake commands (e. g. addcustomcommand(), currently not supported yet), an acceptable workaround may be to invoke shell scripts instead which wrap the commands to be executed. Why do I have unwanted semicolons160 in my compiler flags CMake has a list data type. A list is stored as a string of semicolon-separated list elements. Whitespace separated arguments to a SET statement are interpreted as list elements. For instance, SET(var a b c d e) will give var a value of abcde and this list can be used by other CMake commands. However, if you pass to a non-CMake external tool, such as a compilers command line, you are passing abcde which is not what you want. Instead you either need to pass , so that the list will be converted to a whitespace-separated string, or you need to SET(var a b c d e) in the 1st place so that youre working with a string, not a list. How can I get quoting and escapes to work properly If you want to escape a character in CMake, you use , like in C code. For example, if you wanted to have a quote embedded in a string you would do this: . However, each level of CMake that processes your code will need one level of escaping to work. So, if you configure a file that is read by cmake or cpack and you want to do the same thing, you would do . You would still need to escape the for the first cmake that processes the string. However, this time, you would want to also escape a as well. This would leave the next level of processing with . Also, for custom commands that may get passed to a shell, it maybe required to do escaping for that shell. Isnt the Expression in the ELSE (Expression) confusing Traditional CMakeLists. txt files prior to 2.6.0, require the following syntax. In the IF syntax, the ELSE section requires the same (Expression) as the IF section. This sometimes can make the script kind of hard to follow, take the short example below: You might think that the ELSE section, here containing . do something else. , is for the WIN32 portion of the script. That is not so It is actually handling the NOT WIN32 section. As of CMake 2.6.0 the ELSE() and ENDIF() constructs can be empty. The same is true for closing constructs on ENDMACRO(), ENDFUNCTION(), and ENDFOREACH(). If you require 2.4.x compatibility, CMake 2.4.3 or greater recognizes the CMAKEALLOWLOOSELOOPCONSTRUCTS option (which is superfluous in 2.6.0) Which regular expressions are supported by CMake (for further details, please refer to the original CMake implementation source at Source/kwsys/RegularExpression. hxx. in ) When using MATCHES or MATCHALL in an IF command, or using any of the STRING(REGEX. ) commands, CMake expects regular expressions, not globs (wild cards). CMake uses the same regular expression engine above all platforms. Here are the meanings of the metacharacters: Example: - L(160) matches all strings beginning with - L and ending with a space or a semicolon, the usual linkdirs under Linux. Here is how to catch a part of a string. O teste variável é preenchido com algum conteúdo, e então queremos pegar o me: Isso é um pouco complicado. The part inside the brackets is available in 1. CMake will copy the variable test to the variable result, but then it will replace everything that the regular expression matches with 1. This means the first regular expression has to match the whole string and the part we want to catch has to be put in parens. For those of you who know Perl, the equivalent Perl code could be: There are other ways to do this in Perl, but this is how we do it in CMake because 1 does not become a variable like 1 does in perl, so there is no SET(result ) in CMake. Not sure whether CMake regex implementation supports modifiers for case insensitive matching, thus if this is needed its perhaps best to do matches on a result of string(TOLOWER. ). How to convert a semicolon separated list to a whitespace separated string How can I build multiple modes without switching160 To build multiple modes (e. g. Debug and Release) in one shot without constantly running cmake - DCMAKEBUILDTYPEDebug and cmake - DCMAKEBUILDTYPERelease in source tree create a directory for builds eg. Inside you can place as many target directories for out-of-source build modes as you want, e. g. In each of these directories issue a command (assuming that you have CMakeLists. txt directly in Project-directory) to create a cmake cache configured for requested build type. Now you can make each build just by entering appropriate directory and executing a make command. How can I specify my own configurations (for generators that allow it)160 For generators that allow it (like Visual Studio), CMake generates four configurations by default: Debug, Release, MinSizeRel and RelWithDebInfo. Many people just need Debug and Release, or need other configurations. To modify this, you need to change the variable CMAKECONFIGURATIONTYPES in the cache: Note that the first line checks whether the generator supports multiple configurations. If you just want to add your own configurations while keeping the default ones, you can use list operations: How can I extend the build modes with a custom made one160 The following code snippet (taken from a CMakeLists. txt) adds a Maintainer mode: Notes: The flags used in this example are specific to GCC. Change them as needed for your project. Additionally the SET(CMAKEBUILDTYPE) command will override a CMAKEBUILDTYPE previously set in the CMakeLists. txt. A simple SET(CMAKEBUILDTYPE) does silently overwrite, the change is only visible in the GUI if CACHE is set when overriding. Why does foreach skip empty values The code in question is of the form and the loop variable v never attains the empty-string value . This is because the syntax is an unquoted argument so the CMake language expands the list and removes the empty value. The foreach command does not even see the empty value. One can verify this because the code will see the empty value. Does CMake support precompiled headers Yes and no. Every platform does precompiled headers a bit differently, and there is currently no first-class interface provided by CMake and implemented on every platform. However, CMake does provide enough primitives for projects to use precompiled headers on specific platforms. Our issue tracker has a feature request with attachements providing user-contributed helper macros for some platforms. Writing FindXXX. cmake files What are the rules to write a FindXXX. cmake file Lets follow the instructions and the advices in the Modules/readme. txt 1 file located in the CVS repository. Why does findlibrary look in system directories before its PATHS option The code in question is often of the form CMake will find /usr/lib/libfoo. so instead of /opt/foo/lib/libfoo. so if both exist. The reason is that /opt/foo/lib is a hard-coded guess of the location. The documentation of findlibrary specifies the search order. User, project, and system configuration variables are always more local than hard-coded guesses and should override them, so the PATHS option is used last. Some find-modules compute probable locations based on other information available from the system such as a project-specific environment variable. The HINTS option (CMake 2.6 and higher) takes precedence over system directories specifically for this case: CMake will find ENV /libfoo. so before /usr/lib/libfoo. so . Finding and using external packages How do I use CMake to generate SWIG wrapper libraries CMake version 2 includes a module that supports the generation of SWIG wrapper libraries. The SWIG package defines the following macros: SWIGADDMODULE and SWIGLINKLIBRARIES. If you get errors indicating that C and C include files cannot be found, like, try setting the - includeall property on fewer source files: In particular, you may need - includeall only on the top-level. i files. How do I use CMake to build LaTeX documents Use the following approach. Note that you have to set LATEXCOMPILE to LaTeX executable, DVIPDFCOMPILE to dvi to pdf converter. Also, the LaTeX source is TDocument. tex and the result is called TDocument. pdf. Note that this uses commands in CMake version 1.8 or later. The following uses commands in CMake version 2.0 and later How do I get LaTeX references to be correct When your latex document contains references (e. g. ref command) you get to run two passes of latex. In the most general case, i. e. when additionally your document uses a bibtex bibliography, you shall need three passes of latex (and one pass of bibtex): latex (first pass: for bibtex to have an. aux file) bibtex (for generating the. bbl file) latex (second pass) latex (third pass) The following code snippet illustrates how you can pervert the bibtex and latex generated auxilary files (.aux. log. dvi. bbl. ) to create an artificial set of CMake dependencies. The side-effect of those dependencies should hopefully be the above described sequence of calls to latex and bibtex How can I set TEXINPUTS for a LaTeX compilation First note that most often you can avoid using TEXINPUTS by copying all the necessary files (.tex source file and included graphic files e. g. eps files) from your PROJECTSOURCEDIR hirarchy to your PROJECTBINARYDIR subdir refer to CONFIGUREFILE with the COPYONLY flag set for copying files. Since by default latex uses the current working directory as value for TEXINPUTS you should be all set. As expected, this trick is quick AND dirty since your concerned PROJECTBINARYDIR subdir now contains files that are NOT generated by CMake (in the sense that those files are not the result of a system command but were merely duplicated). If you consider it is cleaner or easier to define a TEXINPUTS environment variable the latex command probably misses a - I flag you can find an example in the InsightDocuments cvs archive (refer to the section cvs access near the bottom of Kitwares ITK download page) or use google with keywords ITKTEXINPUTS CONFIGUREFILE. Look at InsightDocuments/CourseWare/Training/Vis2003/Latex/CMakeLists. txt and search for e. g. LaTeXWrapper. sh. in. Roughly the mechanism goes: SET ITKTEXINPUTS with the desired TEXINPUTS CONFIGUREFILE InsightDocuments/CourseWare/Training/Vis2003/LaTeXWrapper. sh. in which generates an sh shell script setting the shell variable TEXINPUTS prior to running the latex command use ADDCUSTOMCOMMAND to invoke this shell script This very example is Win32 portable (except that LaTeXWrapper. bat. in generates a. bat shell script) Library questions Can I build both shared and static libraries with one ADDLIBRARY command No. Each library you build must have a unique target name, i. e. the libname field of the ADDLIBRARY command. That way, CMake can track dependencies separately for each library. Libraries can have the same OUTPUTNAME, see the SETTARGETPROPERTIES command, but this is not the default. Does that mean I have to build all my library objects twice, once for shared and once for static. I dont like that In practice, most libraries have different defines and compiler flags for the shared vs. static cases. So you would have to build all your library objects twice anyways. However, if you happen to have exactly the same defines and compiler flags for the shared vs. static cases. if youre using Linux and a GCC-style linker, you could do the following. Note that for this to work correctly on linux, the zzSTATIC source files should have been compiled with - fPIC to ensure they will work in a shared library. if you want a cross-platform approach that works on all compilers, not just GCC or Linux, you could extract the locations of previously built object files and insert them directly into the libraries that need them. This is documented in CMake Feature Request 5155: standard way to locate object files. Unfortunately this approach relies on CMakes internal implementation, and that implementation could change in the future, breaking your code. How do I make my shared and static libraries have the same root name, but different suffixes Set the OUTPUTNAME of your shared and static libraries to the same thing. One more detail is needed with CMake 2.6.x and lower (but not CMake 2.8 or higher). If you are building your shared and static libraries in the same directory, you will also need the following to keep your shared and static libraries from clobbering each other during the build. How do I rename a library after it has already been built You dont rename it. Its been built Its name is whatever CMakeLists. txt says its supposed to be. Perhaps you want to copy the library to a different name. But, are you sure thats what you want to do You could just change the name in your ADDLIBRARY command or change its OUTPUTNAME property using SETTARGETPROPERTY(). If you really really want to copy the library to a different name, try: On Windows you may also want to copy the. dll import lib, using the same approach as above, but with IMPORTPREFIX and IMPORTSUFFIX. Problem: LOCATION only refers to 1 file, the. dll. What is a simple way to get the location of the import lib Could provide a complicated way, but thats annoying. Does CMake support convenience libraries No. CMake does not currently support convenience libraries. A convenience library, as GNU libtool calls it, is an archive of objects to be mixed into other libraries. Other libraries link to the convenience library, but the convenience library does not export any symbols GNU libtool never installs the convenience library no programs ever link to the convenience library. This does not mean that a project using convenience libraries cannot be converted to CMake. Instead the source files may be listed in each target that needs them. They will be built for each target separately using all the preprocessor definitions and flags configured for that target. Why are libraries linked to my shared library included when something links to it This question arises when one has a library B which links to some library A. When a third target, say C, links to B, CMake will automatically include C to A also. When the libraries are static, then this is always necessary. When the libraries are shared, this is the default behavior provided by CMake with the simple targetlinklibraries signature. CMake 3.0 and above provide PUBLIC. PRIVATE. and INTERFACE options to targetlinklibraries to specify whether linking should be used for just the implementation and/or made part of the interface (transitive dependencies): CMake 2.8.7 and above provide LINKPUBLIC and LINKPRIVATE options for the same purpose (these were superseded by PUBLIC/PRIVATE/INTERFACE in 3.0 for consistency with options other commands like targetcompiledefinitions ). CMake dependency scanner CMake does not preprocess source files while scanning dependencies. Code like will result in a dependency on bla. h. This sometimes leads to source files recompiling unnecessarily but will not break the build. Installation questions Does CMakes make install support DESTDIR Yes . especially when the build-system generator uses CMakes builtin support for installing files: Simply define the DESTDIR environment variable during installation and CMake will treat that value as the root of the file system for all installation paths naturally, the DESTDIR path must be absolute. For example, if the Makefile generator is used, then all of the following are example usages of DESTDIR (perhaps assuming the bash shell for the last 2): Can I do make uninstall with CMake By default, CMake does not provide the make uninstall target, so you cannot do this. We do not want make uninstall to remove useful files from the system. If you want an uninstall target in your project, then nobody prevents you from providing one. You need to delete the files listed in installmanifest. txt file. Here is how to do it. First create file cmakeuninstall. cmake. in in the top-level directory of the project: Then in the top-level CMakeLists. txt add the following logic: Now you will have an uninstall target at the top-level directory of your build tree. Instead of creating an uninstall target, Unix users could enter this command in the shell: Distribution questions Where is make dist CMake doesnt create a make dist target. What is the best way to distribute source code or binaries for a cmake-based project For creating source or binary packages there is now CPack coming with CMake, see the documentation. Of course you can also use any other ways to create packages. Platform-specific questions How do I build universal binaries on Mac OS X Before running CMake with an empty build tree, set the CMAKEOSXARCHITECTURES environment variable. It should be set to contain a160 separated list of architectures that you want in the binary. For example, for 32-bit PowerPC and Intel you would do this: If you wish to build both as 32 and 64 bit, do this: You can also set the same named CMake cache variable on an existing binary tree. This works with both makefiles and the Xcode generator. In addition, you can also set the CMAKEOSXSYSROOT variable to point to the sysroot (aka Mac OS SDK) to be used. CMake will attempt to pick one on your system, but it can be changed in the cache or via an environment variable before running CMake. The 10.4u SDK or later must be used to create a Universal Binary. Universal Binaries are essentially cross compilation and so you should avoid using TRYRUN, especially for things like testing endianess or variable size because the result will only be correct for one architecture. Lastly, note that CTest is only able to test one architecture. See bug 6157. How can I apply resources on Mac OS X automatically Using ADDCUSTOMCOMMAND. For example, lets say you are creating executable MyExecutable, which needs the resources file Carbon. r. All you do is add a custom rule which is executed after the executable is linked: This will execute: after MyExecutable is linked. Rez may be located elsewhere on disk, depending on the version of Mac OS X and Xcode. You can use which Rez in Terminal to find its full path. Why does FINDLIBRARY not find. DLL libraries under WIN32 For those who come from a Unix background to MS Windows: You never link directly to the. dll, you have to link against the import library. lib for the. dll. Linking against dynamic libraries (.dll under Windows) is quite different from linking against ELF shared objects (.so) under platforms like Linux or NetBSD. In Windows, there are two types of library, a static library and an import library (both confusingly use the. lib extension, however). In Windows, when you build an import library (A. lib) you will get a corresponding (A. dll) that you only need at runtime. At compile time you will need the import library. Conclusion: There is no need to find a. dll for linking. You only need to find the. lib import library. Some more details can be found here: 2. Why am I getting a linker error to mainCRTStartup under WIN32 Your program is a GUI application using WinMain (/subsystem:windows) and not a console application using main. You have to use the WIN32 option with the ADDEXECUTABLE command. The second argument to ADDEXECUTABLE can be WIN32. This indicates that the executable, when compiled on Windows, is a Windows app (using WinMain) and not a console app (using main). Please note that on Unix platforms, CMake ignores the WIN32 and the compiler will use main in any case. Why do I get this error: nafxcwd. lib(appcore. obj)160: error LNK2001: unresolved external symbol argv This is because the application is using both the static and dll versions of the MFC library. To fix the problem, you can do the following: How to use MFC with CMake To use MFC, the CMAKEMFCFLAG variable must be set as follows: This can be set in a CMakeLists. txt file and will enable MFC in the application. It should be set to 1 or 2. This is used in visual studio 6 and 7 project files. The CMakeSetup dialog uses MFC and the CMakeLists. txt looks like this: Note that visual studio 9 project files do not appear to work with CMAKEMFCFLAG 1 this may be related to bug 7056. In order to use MFC with UNICODE, you must also specify the entry point wWinMainCRTStartup. For example: See this article as to why BINDTOCURRENTCRTVERSION and BINDTOCURRENTMFCVERSION are necessary for Visual Studio 2008 SP1. How To Put Files in Folders in Visual Studio Projects The Visual Studio IDE supports putting files into folders. CMake can be used to put files in folders with the SOURCEGROUP command. Defines a group into which sources will be placed in project files. This is mainly used to setup file tabs in Visual Studio. Any file whose name is listed or matches the regular expression will be placed in this group provided the source file is being passed to ADDEXECUTABLE or ADDLIBRARY. In the event a file matches multiple groups, the LAST group that explicitly lists the file will be favored, if any. If no group explicitly lists the file, the LAST group whose regular expression matches the file will be favored. For backwards compatibility this command is also supports the format SOURCEGROUP(name regex). As a convenience to developers CMake automatically adds standard header files to a Header Files folder and standard source files to a Source Files folder for Visual Studio Projects. This can be overridden via the SOURCEGROUP method documented above. How to create Visual Studio 6 Projects that contain only a single build type For Visual Studio (version 7.0 and above) it is possible to set the CMAKECONFIGURATIONTYPES variable to the build type(s) (Debug/Release/. ) that you want. This does not work for Visual Studio 6. There is however a way to achieve this. To create your own set of configurations: Create a directory in which you copy the files. dsptemplate and CMakeVisualStudio6Configurations. cmake from CMakes Templates directory. Edit the. cmake file and change the SET(CMAKECONFIGURATIONTYPES. ) line to set the build types that you want in your set. Edit the Header. dsptemplate files to contain only the configuration types you want in your set. In your CMakeLists. txt file, set the MSPROJECTTEMPLATEDIRECTORY to the directory that you created. É isso aí. Run CMake and your new configuration files will be created. Note: Editing the Header. dsptemplates files should be done very carefully. Here are some guidelines: - You MUST remove the targets that you do not want in your set at the bottom of the file (e. g. Name OUTPUTLIBNAME - Win32 MinSizeRel) - You can remove the IF (CFG) . until ELSEIF (CFG) . or ELSEIF (CFG) . until ENDIF lines for the configurations you do not want. Make sure that the resulting code still starts with IF. and ends with ENDIF with any number of ELSEIF sections in between. If you create templates for a single configuration (aka makefile), it is possible to remove everything starting from IF until and including ENDIF and leave only the contents of the relevant section intact. - Do not edit the lines starting with MESSAGE as the changes may - and probably will - corrupt your resulting DSP files. The only thing I was able to change without corrupting the DSP is to remove the irrevant configurations from the Possible choices for configuration are: list. If you have only a single configuration in your set, you may want to get rid of the intermediate dir that MsDev creates. You can do that by setting: PROP BASE OutputDir PROP BASE IntermediateDir PROP IntermediateDir PROP OutputDir LIBRARYOUTPUTPATH PROP OutputDir EXECUTABLEOUTPUTPATH Additionally you should then also edit the ADD LINK32 line in the DLLHeader. dsptemplate file. Change for example /out:LIBRARYOUTPUTPATHDebug/OUTPUTLIBNAMEDEBUGPOSTFIX. dll into /out:LIBRARYOUTPUTPATHOUTPUTLIBNAMEDEBUGPOSTFIX. dll (Note that the configuration name and also the slash are removed). It is even possible to rename the pre-defined configurations of CMake in this way. Lets say you prefer PreProduction over RelWithDebInfo. You can change the name in the. dsptemplate files, but you should also change it in the CMakeVisualStudio6Configurations. cmake file. Be careful, however. Only entries relevant to the configuration name should be changed. Do not change the /debug options and the entries that contain the build type in capital characters. Internally in CMake the build type will still remain RelWithDebInfo, so also the CMAKEBUILDTYPE should be set to the old value. You can only change the way it is named in MSDev. Note: Apparently MsDev as command-line build tool only performs a partial check on the build type. It will match all configuration types that CONTAIN the build type in their name. (e. g. if you have renamed RelWithDebInfo to DebugRelease, Debug will build Debug and DebugRelease, Release will build Release and DebugRelease. This may be exactly what you want, but be warned.) Can CMake set the Debugging/Working Directory property in Visual Studio projects Not directly. The value of this property is not stored in the project files. It is stored in extra files created by the IDE when a solution is loaded (VS 2003 uses a hidden. suo file next to the. sln solution file). The format of these files is not known to CMake and cannot be generated. In some versions of VS the files are binary and not human readable. However, for Visual Studio versions at least 2005 and newer, Ryan Pavlik maintains CMake modules that can create these files: main script. also requires this directory. Why does CMakeSetup with the message LINK160: fatal error LNK1104: cannot open file user32.lib while configuring a project The path to the SDK libs (user32.lib) must be added by the IDE when the project generator Visual Studio 8 2005 is used, because cmake uses VCExpress. exe and on the fly generated project files to check for compiling (VCExpress. exe reads some config files for the compiler/linker options) So add the sdk lib path (. Microsoft Platform SDKLib) at Tools-gtOptions-gtProjects and Solutions-gtVC Directories-gtLibrary files How can I avoid the error Arg list too long when running make This error is sometimes encountered when building a static library with many object files using Unix make command. It typically looks something like this: When make tries to run the archiver program to build the static library the shell it uses complains that the argument list is too long. In some shells this can be fixed by setting an environment variable such as ARGMAX to extend the length of the command line it will allow. The error can also happen when linking shared libraries, and can be solved by upping the sysconf parameter MAXARG. On AIX this can be done with the command: Obviously an alternative approach might be to contemplate reducing the object count by splitting off some suitable group of objects into their separate static library. How can I find out platforms definitions, search paths, etc. from gcc160 The following is really the best if not only way to get information about predefined macros with a GNU compiler: This will give you all you might want to know about the preprocessor, the builtin include search dirs and all predefined definitions, so you can check whether its LINUX or LINUX or APPLE or APPLE etc. The empty file and all these parameters are really required. You probably want to pipe the output (both stdout and stderr) to a file. If you want the information for C, use a C file suffix for the empty file. This is how you can get the builtin library search paths: How can I get a windows registry key160 The only thing to know is that you cant use just the SET command in place of GET command. CMake read the value from the registry only when you get it from the cache. For instance160: If a key name (ex: InstallDir in this case) was not specified. the Default key value will be get. Now you could use the SDKROOTPATH to add include and lib path to your project160: You can also read a registry key in the PATHS section of a FINDLIBRARY, FINDPATH, FINDPROGRAM, or FINDFILE command For other examples have a look in the CMake Modules folder160: How can I build my MSVC application with a static runtime Here are three options you could employ to compile your MSVC application with /MT instead of /MD. Manual Replace You can rely on the user to manually modify CMAKECFLAGSDEBUG, CMAKECFLAGSRELEASE, CMAKECXXFLAGSDEBUG, CMAKECXXFLAGSRELEASE, etc. within the cache editor. After an initial configure of your software they would have to replace /MD entries with /MT. Make Override Files If you intend to build the entire source tree using /MT and you dont need this ever to be configurable via the CMake GUI, the best approach is to create an override file which initializes the starting cache values for the compile flags. First create a cflagoverrides. cmake amp cxxflagoverrides. cmake file which contain something like this. (or whatever flags you wish to use per compiler). NOTE: These files are only evaluated on the first run of CMake so they cant be dependent on a CMake option() meant to be toggled from the GUI, for example. They could be dependent on a command line - D option or an environment variable if desired. Then enable them by setting the following variables prior to the project() command. Dynamic Replace Alternatively, if you need dynamic control of /MT via some configure option you could use the following technique. Note: CMAKECXXFLAGSltFOOgt is a directory level option, however. Also, this option has the downside of leaving /MD visible in the cache editor although it has no effect. Why do generated Xcode projects have a CMake PostBuild Rules phase CMake needs precise control over target link command lines that Xcode runs at build time. Xcode provides a Link Binary With Libraries build phase in which one may list files or products from other targets to include when linking. However, it does not allow arbitrary flags such as - lfoo commonly passed by projects to CMakes targetlinklibraries command. It also does not allow full paths to library files and instead splits /path/to/libfoo. a into - L/path/to and - lfoo which does not guarantee the proper library will be found. CMake works around this limitation by putting the entire link line in the OTHERLDFLAGS build setting where it has full control. Unfortunately that build setting is just a string, so the resulting build system has no dependency on the files named in the link line. Furthermore, Xcode does not have any build setting to list arbitrary extra dependencies of the link step. If any of a targets dependencies are newer than the targets binary Xcode does not know it needs to run the link rule again to bring the target up to date. In order to work around the dependency problem, CMake includes in each target a post-build phase that removes the link outputs of all other targets that depend on the current target. This is necessary because all those other targets lack dependencies on the current target in the generated build system. Instead when a target finishes building it knows that any other targets that depend on it will be out of date. The post-build phase removes the other targets so that when it is their turn to build Xcode will re-link them. The post-build phase could be avoided if Xcode were to simply provide a setting to specify link dependencies on arbitrary files. This feature would be useful independent of CMake as it would allow users to add dependencies on files they mention in OTHERLDFLAGS. Why does CMake not find my Xcode compiler on OS X with the Unix Makefiles generator Xcode 4.3 and later do not install the command-line development tools by default. One must also install the Command Line Tools for Xcode package. As of Xcode 4.4 one may install it from the Xcode menu: As of Xcode 4.5 the command-line tools are also available as an independent download that does not require the full Xcode. It is also possible to set up a shell environment to run cmake and make without installing the Command Line Tools package. CMake 2.8.10 and greater will recognize when the command-line tools are not installed, find the MacOSX SDK, and add the - isysroot flag. One may use the environment: The above environment will work with CMake 2.8.8 and 2.8.9 if one also specifies architectures explicitly (earlier CMake versions are not aware of Xcode 4.3 SDKs): Alternatively one may add - isysroot flags via the environment: Other Questions Why does CMake generate recursive Makefiles This question is often asked with reference to this paper: The summary of our response may be worded recursive make considered necessary. CMake must generate makefiles that invoke other makefiles in order to implement automatic implicit dependency scanning in combination with generated source/header files. Since CMake works with primitive UNIX make tools we may not use GNU make extensions to load new make rules into an already-running make process. CMake does not actually generate truly recursive makefiles that follow the directory structure. It generates a fixed 3-level makefile structure in which each level has a defined purpose: Makefile . Command-line interface entry points. Maps make invocations into calls to the level 2 makefile: make - f CMakeFiles/Makefile2. CMakeFiles/Makefile2 . Inter-target dependencies. Evaluates targets in dependency order invoking for each target the depends and build steps in level 3: make - f CMakeFiles/(target).dir/build. make. /depend make - f CMakeFiles/(target).dir/build. make. /build CMakeFiles/lttargetgt. dir/build. make . File-level dependencies and rules: depend. Evaluates custom commands (to produce generate source files) and then scans sources for implicit dependencies. build. Loads dependency scanning results from previous step. Compiles and links. As a flat-file, minimalistically-designed command-line build alternative to make, using the newly-added (2012) Ninja generator might be worthwhile. Why cant I make multiple targets on the command line in parallel The Makefiles generated by CMake do not support explicit specification of multiple targets on the command line as because it was not a design goal at the time the generators were written. Insead use or use addcustomtarget and adddependencies to create a single target depending on both targets and then make that. See the multi-level makefile layout described in the answer to the above question. Its the first levels invocation of the second level that needs to be re-worked and perhaps combined in order to fix this limitation. However, the first level is what allows one to run make from any subdirectory to build the targets there along with dependencies so there must be a separate Makefile in each directory. Supporting both at the same time is not a trivial change from the current design. See issue tracker entry 14312. Any proposed solution must work with ancient UNIX make and cannot depend on GNU make features. by Johan Petersson Linking libstdc statically Christopher Baus writes about his problems linking libstdc statically. Yes, making C binaries that will work properly in different Linux distributions is somewhat painful. The problem is not so much linking libstdc statically it is just a library, after all but the runtime support required by C code in general, to enable features like RTTI and exception handling. The runtime support code used by different parts of a C application needs to be compatible. If one part of the program needs to dynamiccast or catch objects provided by another, both parts must agree on certain implementation details: how to find vtables, how to unwind the stack, and so on. For C and a few other GCC - supported languages with similar features, such details are specified by a C ABI. Whenever the ABI used by GCC changes youll end up with incompatible libraries produced by the different GCC versions. The same is true for plain C, but the C ABI is much simpler and has been around a lot longer so its fairly stable. As far as I know C ABI changes have been introduced with every major release of GCC (i. e. those with different first or second version number components). To make matters worse, most major Linux distributions use GCC snapshots and/or patch their GCC versions, making it virtually impossible to know exactly what GCC versions you might be dealing with when you distribute binaries. Note that this problem cannot, in general, be solved by linking statically. First of all, code compiled against different ABIs is simply not binary compatible. It doesnt matter if you manage to link binary incompatible code together, because it will never work properly. Secondly, the language runtime support typically rely on some data being shared, e. g. to access some kind of lock or global data structure (similar to how C programs need a shared errno ). Shared data implies that whenever more than one part of a program needs the runtime support, and any of those parts is dynamically loaded, the runtime support needs to be loaded dynamically too. Otherwise, the different program parts would end up with copies of the data rather than one shared instance. Thats the reason for putting the language runtime support code in a dynamic library by default. There are many different workarounds and no perfect solution, but a fairly workable compromise is to link all C code into an executable while using dynamically loaded C libraries only. This way there is only one part of the program that needs the C runtime support mechanisms, which can therefore be linked in statically. You can mix and match statically and dynamically linked C libraries, but no C code (or any code using the C runtime support) may be linked dynamically if this is to work. Now, the practical problem people run into when trying to link libstdc statically is that g. the GCC front-end for compiling and linking C, adds the proper libraries and start-up code for C automatically and will link some of this code dynamically by default: The resulting binary links to a shared version of libstdc, the standard C library, and a shared version of libgcc, a GCC runtime support library required for exception handling among other things. This binary wont work on a machine with different versions of those libraries, but since it doesnt need any other dynamically loaded C libraries, the incompatibility can be removed by linking libstdc and libgcc statically. Consulting the GCC man page, youll find the GCC option - static-libgcc mentioned. It makes the compiler link libgcc statically rather than dynamically. Except when it doesnt: What happened here Remember what I said earlier about not loading any C code dynamically Since we are still linking dynamically to libstdc, the runtime support code in libgcc must also be linked dynamically. g ignored the - static-libgcc flag because linking libgcc statically would not result in a program that works properly. We need to link statically to both libraries, or neither. You can ask g to tell you exactly what steps are involved in linking a C program (try the - v flag if you are curious) and invoke a slightly different set of commands in order to link your application with static versions of libstdc and libgcc. But integrating that into your own build process is painful, error-prone, and specific to the machine and compiler version you use. Theres no - static-libstdc option to go along with - static-libgcc. but you can let the compiler tell you the path to the static libstdc library it would use, and let g look for libraries in a directory where it will only find the static version (in this case our build directory): Once again, for this to work reliably you must not use dynamically loaded C code, including code loaded with dlopen. In particular, statically linking the runtime support code is contraindicated when creating dynamically loadable C libraries. Depending on your linker it might be possible, but planning to distribute such binaries is still very much an order for a super-sized can of worms. Update: As of GCC 4.5 there is now a - static-libstdc compiler option which does what youd expect it to do. (Thanks to Tim Hutt for pointing this out.) by christopher baus Johan. Thanks for addressing this. I understand the problem of using. sos that were compiled against different version of libstdc. But this can be avoided by statically linking the entire executable (minus libc). The end result I believe is better for the user and the maintainer (me). By statically linking there are no external dependencies that must be satisfied. Your executable ends up a bit bigger, but in my case it isnt that bad. What I found extraordinarily frustrating is that - static-libgcc fails silently. Im still confused by your solution to use - L/some/path/to/libstdc/. The only way to get gcc to statically link is to physically move the library by Johan Its certainly not the only way, just the easiest way I know of. I only need to make that libstdc. a symlink a target in my makefile and let g know where to look for it. The alternatives generally require quite a few link and library options specified in the right order and I find that tricky to get right. by Garrett Rooney Note that linking C code statically does have some issues beyond what Ive seen you guys discuss. Specifically, nondeterministic ordering of global object instantiation can be a problem. Say youve got on global object in one library, and another in another library, and within their constructors they manage to do something such that one depends on the other. In a statically linked world you can end up in situations where a global object is used before its constructor is actually called, which needless to say is a bad thing. The root cause is the fact that the order in which the global object constructors is called in is fixed (and arbitrary), and is not dependant on their interdependencies. In a dynamically linked world, you can get around the problem by forcing the runtime linker to handle the ordering, you wrap object access in a function of some sort, and when that function is called the runtime linker pulls in the other library, which causes the constructor to be called early enough. I realize this isnt the kind of problem youre trying to solve, but Im just trying to point out that static linking isnt the end-all be-all solution to all problems in C land. by Johan There are no guarantees regarding static object initialization order in C its a limitation in the language. If a C program or library needs a certain order of initialization to work correctly its relying on inherently nonportable platform features, and developers had better already be aware that this always come at the cost of fragile code. by Ken MacLeod (/me adds another blog to the feed reader, thanks) While I can understand the desire to release distribution-agnostic binaries -- I mean, if youre going to distribute binaries, why not for as many platforms as possible -- what I dont yet understand is how the quotlast 20quot is handled: differences in the runtime environment outside the code itself. Ou seja. filesystem layout, startup/shutdown scripts, logging, integration, etc. It would seem to me that theres only a quotnichequot between programs small enough that can dynamically link against several distributions and programs large enough that the environment outside the executable is just as important. Am I missing something by christopher baus The RedHat like distributions all basically use the same rc scripts and filesystem layouts, but they have different versions of libstdc. Thats one reason. I also like to know exactly what I am linking to. In Windows this particularily becomes a nightmare since DLLs arent versioned. Plus you dont require users to resolve dependencies, which requires root access. by Mike Hearn Statically linking libgccs is probably not a good idea: for one, every GCC 3.x version provides it and AFAIK it has not changed incompatibly. For another, it gives you a silent dependency on newer versions of glibc (go have a look at the registerframeinfobases symbol your binary just acquired). For the autopackage project, we force dynamic linking of libgccs and place it on the system at install time if its not there. by Matt Hall THANK YOU SO MUCH You saved me from a project rollout disaster this evening brought on by a conflict between a 32-bit and a 64-bit libgcc. by Karl Berry I recently had this same problem, wanting to link libstdc statically. Since this web page was helpful reading, I thought Id post my solution (so far). Maybe someone will find it useful. This was for TeX Live. which includes the lcdf-typetools. which are written in C. TL distributes binaries. I need not explain the resulting pain to anyone reading here :). I didnt want to have to set up a separate directory as discussed above, since (because of libc incompatibilities, sigh) mine is not the final build machine. I found that I could get static linking by using gcc instead of g as the front-end, as in the following one-line script: Then I tell automake to use it, say its named cxxhack: (well, for TL its actually several layers away from a direct configure call, but that doesnt matter here.) Explanation: it turns out that (incredibly annoyingly) g does not use the specs file to determine the final link command 8211 the stdc part is hardwired into the binary, and no environment variable or runtime configuration can change it, as far as I could see. (gcc-3.4.4/gcc/cp/gspec. c, line 303 or so). Thus, the idea is to use gcc instead of g or c for the front-end compiler, and link with - lstdc ourselves. g / c automatically link with - lm. so we do that too. Perhaps there is a cleaner way to alter the lcdf configure setup to achieve the same link line, but I could not find it offhand. I wrote to bug-automake for advice. Some of the output from configure looked doubtful (quotno - lstdcquot), but the binaries seemed to run. and ldd reports no libstdc. Hallelujah. I surmise that this wont work in the face of exceptions or other issues as mentioned here, but Im hoping it will suffice for us. If anyone has any comments or better suggestions, Id be grateful to hear. My email is karlfreefriends. org. by marvind I tried the following command on RedHat Enterprise Linux 3.0 gcc - o example example. cpp /usr/lib/gcc-lib/i386-redhat-linux/3.2.3/libstdc. a (the library path from the output of g - print-file-namelibstdc. a as you pointed out). The output of ldd is: marlocalhost testldd example libc. so.6 gt /lib/tls/libc. so.6 (0xb749e000) /lib/ld-linux. so.2 gt /lib/ld-linux. so.2 (0xb75eb000) Looks like it linked the gcc version correctly. Note that I did not specify the location. of libgcc at all. So, I am not sure why I have to specify the - Bstatic, etc. I have the libstdc. so in the usual location under /usr/lib with libgcc. so under /lib. I would appreciate a clarification. Obrigado. by Johan marvind, you are compiling and linking C code with gcc rather than g. Thats not guaranteed to work, for precisely the reasons I mention at the beginning of my post. Even if you get no errors during compiling and linking, your executable may fail unexpectedly when using certain C features. by Tony Feick Have you had any problems trying to static link libpthread by Dmitry Johan, thanks for your wonderful note. If I understand correctly, this approach will not work if I would like to link my SO library against STDC statically (because all object files in libstdc. a are compiled with no - fpic). Am I right What is the way out by Andrew Schetinin Thanks for a very good article. Im currently having a similar task, and found a bunch of troubles on the way, in addition to what you has here. Some older Linuxes had bugs in libstdc. a (there was a symbolic link pointing to non-existing file, or there were missing symbols) - that was solved by applying recent patches. We also wanted to compile our code with gcc 4.1.2 at least on RedHat 5, and still be able on RedHat 4 (which has the same version of libstdc but older GLIBC). There is no problem with that as long as you link to libstdc. so (as long as no newer GLIBC features are used, and - Wl, hash-styleboth is supplied. But it does not work so with static linkage to libstdc anymore, since there is no way to work around those new GLIBC symbols. To Dmitry: Strangely, 32 bit libstdc does not cause any problems when linking statically to it, but 64 bit libstdc is not so good - it fails to link into a shared library. There is a very good page Ive found on the subject, which explains that - by Varun Muralidharan This article was very interesting. Please do come with more articles

No comments:

Post a Comment