C/C++
Inclusão de libs no CMAKE

Muitas vezes temos que incluir libs e fontes no nosso projeto no CMAKE.

Irei mostrar como faze-lo.

Crie seu código CMakeLists.txt

cmake_minimum_required (VERSION 3.8)
project(projeto VERSION 1.0)
include_directories("."	"./include")
set(CMAKE_CXX_STANDARD 14)

#adicionando libs
add_library(lib1 SHARED IMPORTED)
set_property(TARGET lib1 PROPERTY IMPORTED_LOCATION "./libs")

add_library(lib2 SHARED IMPORTED)
set_property(TARGET lib2 PROPERTY IMPORTED_LOCATION "./libs2")

add_executable(projeto mainsource.c source1.c)

Pronto vc incluiu libs

C/C++ cmusphinx IA
Montagem de código em C com Ninja

Definição

Ninja é um pequeno conjunto de ferramentas, desenvolvido por Evan Martin, um empregado da Google. Ninja foi usado em diversas construções de aplicações.

Entre suas vantagens estão a facilidade de montagem de aplicação, a velocidade e rapidez.

Outra vantagem é a capacidade de construir aplicações em multiplos SOs. (Windows, Linux, MacOS).

Referência:

https://en.wikipedia.org/wiki/Ninja_(build_system)

NINJA

Construção

Iremos apresentar um pequeno projeto construído com NINJA.

O srvOuve é um projeto que visa integrar o CMU sphinx, estaremos construindo uma build com ninja.

Primeiramente precisamos criar o arquivo CMakeLists.txt , que fará a magica acontecer.

Criamos o arquivo conforme aparece no fragmento abaixo:

cmake_minimum_required (VERSION 3.8)

#Define o projeto
project(srvOuve VERSION 1.0)

#Diretorios de Include
include_directories(	   "/usr/local/include/pocketsphinx"
						   "/usr/local/include/sphinxbase"
                          )

set(CMAKE_CXX_STANDARD 14)

add_executable(srvOuve ouve.cpp)

Agora precisaremos dizer ao sistema para gerar os arquivos do ninja, para tanto chamamos o cmake, conforme a sintaxe abaixo:

$ cmake -G Ninja

Execução na console

Com este passo o cmake criará dois arquivos:

build.ninja – Este arquivo contem as configurações de compilação (build)

O build.ninja conterá as regras de construção da aplicação.

# CMAKE generated file: DO NOT EDIT!
# Generated by "Ninja" Generator, CMake Version 3.10

# This file contains all the build statements describing the
# compilation DAG.

# =============================================================================
# Write statements declared in CMakeLists.txt:
#
# Which is the root file.
# =============================================================================

# =============================================================================
# Project: srvOuve
# Configuration:
# =============================================================================

#############################################
# Minimal version of Ninja required by this file

ninja_required_version = 1.5

# =============================================================================
# Include auxiliary files.


#############################################
# Include rules file.

include rules.ninja


#############################################
# Utility command for rebuild_cache

build CMakeFiles/rebuild_cache.util: CUSTOM_COMMAND
  COMMAND = cd /home/maurinsoft/projetos/srvOuve/srv && /usr/bin/cmake -H/home/maurinsoft/projetos/srvOuve/srv -B/home/maurinsoft/projetos/srvOuve/srv
  DESC = Running CMake to regenerate build system...
  pool = console
  restat = 1
build rebuild_cache: phony CMakeFiles/rebuild_cache.util
# =============================================================================
# Object build statements for EXECUTABLE target srvOuve


#############################################
# Order-only phony target for srvOuve

build cmake_object_order_depends_target_srvOuve: phony
build CMakeFiles/srvOuve.dir/ouve.cpp.o: CXX_COMPILER__srvOuve ouve.cpp || cmake_object_order_depends_target_srvOuve
  DEP_FILE = CMakeFiles/srvOuve.dir/ouve.cpp.o.d
  FLAGS = -std=gnu++14
  INCLUDES = -I/usr/local/include/pocketsphinx -I/usr/local/include/sphinxbase
  OBJECT_DIR = CMakeFiles/srvOuve.dir
  OBJECT_FILE_DIR = CMakeFiles/srvOuve.dir

# =============================================================================
# Link build statements for EXECUTABLE target srvOuve


#############################################
# Link the executable srvOuve

build srvOuve: CXX_EXECUTABLE_LINKER__srvOuve CMakeFiles/srvOuve.dir/ouve.cpp.o
  OBJECT_DIR = CMakeFiles/srvOuve.dir
  POST_BUILD = :
  PRE_LINK = :
  TARGET_FILE = srvOuve
  TARGET_PDB = srvOuve.dbg

#############################################
# Utility command for edit_cache

build CMakeFiles/edit_cache.util: CUSTOM_COMMAND
  COMMAND = cd /home/maurinsoft/projetos/srvOuve/srv && /usr/bin/cmake-gui -H/home/maurinsoft/projetos/srvOuve/srv -B/home/maurinsoft/projetos/srvOuve/srv
  DESC = Running CMake cache editor...
  pool = console
  restat = 1
build edit_cache: phony CMakeFiles/edit_cache.util
# =============================================================================
# Target aliases.

# =============================================================================
# Folder targets.

# =============================================================================
# =============================================================================
# Built-in targets


#############################################
# The main all target.

build all: phony srvOuve

#############################################
# Make the all target the default.

default all

#############################################
# Re-run CMake if any of its inputs changed.

build build.ninja: RERUN_CMAKE | /usr/share/cmake-3.10/Modules/CMakeCInformation.cmake /usr/share/cmake-3.10/Modules/CMakeCXXInformation.cmake /usr/share/cmake-3.10/Modules/CMakeCommonLanguageInclude.cmake /usr/share/cmake-3.10/Modules/CMakeGenericSystem.cmake /usr/share/cmake-3.10/Modules/CMakeLanguageInformation.cmake /usr/share/cmake-3.10/Modules/CMakeSystemSpecificInformation.cmake /usr/share/cmake-3.10/Modules/CMakeSystemSpecificInitialize.cmake /usr/share/cmake-3.10/Modules/Compiler/CMakeCommonCompilerMacros.cmake /usr/share/cmake-3.10/Modules/Compiler/GNU-C.cmake /usr/share/cmake-3.10/Modules/Compiler/GNU-CXX.cmake /usr/share/cmake-3.10/Modules/Compiler/GNU.cmake /usr/share/cmake-3.10/Modules/Platform/Linux-GNU-C.cmake /usr/share/cmake-3.10/Modules/Platform/Linux-GNU-CXX.cmake /usr/share/cmake-3.10/Modules/Platform/Linux-GNU.cmake /usr/share/cmake-3.10/Modules/Platform/Linux.cmake /usr/share/cmake-3.10/Modules/Platform/UnixPaths.cmake CMakeCache.txt CMakeFiles/3.10.2/CMakeCCompiler.cmake CMakeFiles/3.10.2/CMakeCXXCompiler.cmake CMakeFiles/3.10.2/CMakeSystem.cmake CMakeLists.txt
  pool = console

#############################################
# A missing CMake input file is not an error.

build /usr/share/cmake-3.10/Modules/CMakeCInformation.cmake /usr/share/cmake-3.10/Modules/CMakeCXXInformation.cmake /usr/share/cmake-3.10/Modules/CMakeCommonLanguageInclude.cmake /usr/share/cmake-3.10/Modules/CMakeGenericSystem.cmake /usr/share/cmake-3.10/Modules/CMakeLanguageInformation.cmake /usr/share/cmake-3.10/Modules/CMakeSystemSpecificInformation.cmake /usr/share/cmake-3.10/Modules/CMakeSystemSpecificInitialize.cmake /usr/share/cmake-3.10/Modules/Compiler/CMakeCommonCompilerMacros.cmake /usr/share/cmake-3.10/Modules/Compiler/GNU-C.cmake /usr/share/cmake-3.10/Modules/Compiler/GNU-CXX.cmake /usr/share/cmake-3.10/Modules/Compiler/GNU.cmake /usr/share/cmake-3.10/Modules/Platform/Linux-GNU-C.cmake /usr/share/cmake-3.10/Modules/Platform/Linux-GNU-CXX.cmake /usr/share/cmake-3.10/Modules/Platform/Linux-GNU.cmake /usr/share/cmake-3.10/Modules/Platform/Linux.cmake /usr/share/cmake-3.10/Modules/Platform/UnixPaths.cmake CMakeCache.txt CMakeFiles/3.10.2/CMakeCCompiler.cmake CMakeFiles/3.10.2/CMakeCXXCompiler.cmake CMakeFiles/3.10.2/CMakeSystem.cmake CMakeLists.txt: phony

#############################################
# Clean all the built files.

build clean: CLEAN

#############################################
# Print all primary targets available.

build help: HELP




O cmake tambem cria o arquivo rules.ninja, responsável pelas regras de compilação.

# CMAKE generated file: DO NOT EDIT!
# Generated by "Ninja" Generator, CMake Version 3.10

# This file contains all the rules used to get the outputs files
# built from the input files.
# It is included in the main 'build.ninja'.

# =============================================================================
# Project: srvOuve
# Configuration:
# =============================================================================
# =============================================================================

#############################################
# Rule for running custom commands.

rule CUSTOM_COMMAND
  command = $COMMAND
  description = $DESC


#############################################
# Rule for compiling CXX files.

rule CXX_COMPILER__srvOuve
  depfile = $DEP_FILE
  deps = gcc
  command = /usr/bin/c++  $DEFINES $INCLUDES $FLAGS -MD -MT $out -MF $DEP_FILE -o $out -c $in
  description = Building CXX object $out


#############################################
# Rule for linking CXX executable.

rule CXX_EXECUTABLE_LINKER__srvOuve
  command = $PRE_LINK && /usr/bin/c++  $FLAGS  $LINK_FLAGS $in  -o $TARGET_FILE $LINK_PATH $LINK_LIBRARIES && $POST_BUILD
  description = Linking CXX executable $TARGET_FILE
  restat = $RESTAT


#############################################
# Rule for re-running cmake.

rule RERUN_CMAKE
  command = /usr/bin/cmake -H/home/maurinsoft/projetos/srvOuve/srv -B/home/maurinsoft/projetos/srvOuve/srv
  description = Re-running CMake...
  generator = 1


#############################################
# Rule for cleaning all built files.

rule CLEAN
  command = /usr/bin/ninja -t clean
  description = Cleaning all built files...


#############################################
# Rule for printing all primary targets available.

rule HELP
  command = /usr/bin/ninja -t targets
  description = All primary targets available:

Para processar o ninja precisamos fazer uma pequena mudança, alterar as extensões de .c para .cpp, para que o sistema identifique que se trata de compilador C.

Incluindo dependências

Para incluir diretorios para Include, basta incluir a linha

Diretórios de Include

include_directories( “/usr/local/include/pocketsphinx”
“/usr/local/include/sphinxbase”
)

Include adicional

Gerando binário

Por fim precisaremos dar o comando ninja para compilar os scripts.

$ ninja

Pronto você montou um Montador em Ninja! Parabéns!

Sem categoria
CMake no KDevelop

O CMake é um conjunto de ferramentas multi plataforma, destinada a geração automatizada de programas. Ele é usando em conjunto com o compilador, orquestrando compilações complexas.

Iremos abordar aqui um exemplo simples de código, integrado com o KDevelop.

Fontes do projeto

Iremos explicar como criamos nosso projeto.

Primeiramente crie um projeto c, conforme apresentado no tutorial do link a seguir:

http://maurinsoft.com.br/index.php/2021/02/12/kdevelop-novo-projeto/

Em seguida, entre no projeto teste02, e com o botão direito, abra o menu, conforme apresentado a seguir:

Agora selecione a opção create file, conforme figura acima.

Digite os funcoes.c, depois repita a mesma operação com funcoes.h.

Agora temos no projeto, conforme o exemplo abaixo:

Neste exemplo temos dois fontes:

  • main.c
  • funcoes.c

O main.c usa uma função do funcoes.c, iremos ver como incluir isso no CMAKE.

Copie os códigos para os respectivos fontes, conforme apresentado.

Fonte do main.c:

#include <stdio.h>
#include <stdlib.h>
#include “funcoes.h”

int main(int argc, char *argv[])
{
teste1();
return 0;
}

Fonte do funcoes.c:

#include “funcoes.h”
#include <stdio.h>
#include <stdlib.h>
void teste1(void)
{
printf(“Teste funcoes”);
}

Fonte do funcoes.h:

#ifndef FUNCOES_H
#define FUNCOES_H
void teste1(void);
# endif /FUNCOES_H/

Exemplo do CMakeList.txt

cmake_minimum_required(VERSION 3.0)
project(teste02 LANGUAGES C)
include_directories(include)
set(CMAKE_C_FLAGS “-Wall”)
file( GLOB SRCS *.c *.h)
add_executable(teste02
main.c
funcoes.c
)
install(TARGETS teste02 RUNTIME DESTINATION bin)

Agora vem a explicação do CMAKE

O cmake_minimum_required diz a versão mínima do cmake exigida para executar o script.

project diz, qual linguagem é o alvo que iremos compilar. Neste caso indiretamente dizemos também o compilador e informações a respeito de linkagem.

include_directories, diz para incluirmos o diretório corrente.

Já o comando set, avisa o compilador para ativar o parâmetro -Wall

O file pesquisa, como fonte qualquer arquivo de extensão .c ou .h;

E por fim add_executable, monta o binário (executável) a partir dos arquivos .c adicionados.

O install, cria um fluxo de instalação. Já é o processo tipo make install.

maurinsoft.com.br