Connectivity maintenance is an essential aspect to consider while controlling a multi-robot system. In general, a multi-robot system should be connected to obtain a certain common objective. Connectivity must be kept regardless of the control strategy or the objective of the multi-robot system. Two main methods exist for connectivity maintenance: keep the initial connections (local connectivity) or allow modifications to the initial connections, but always keeping the overall system connected (global connectivity). In this paper we present a method that allows, at the same time, to maintain global connectivity and to implement the desired control strategy (e.g., consensus, formation control, coverage), all in an optimized fashion. For this purpose, we defined and implemented a Control Barrier Function that can incorporate constraints and objectives. We provide a mathematical proof of the method, and we demonstrate its versatility with simulations of different applications.